First Repeating Element in an Array (C++)

Published: (January 13, 2026 at 12:06 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Why My First Approach Was Wrong — and How I Fixed It

Problem Clarification (Very Important)

The task is to find the element whose first occurrence index is smallest among all repeating elements.
It is not:

  • the smallest value
  • just any duplicate

Order matters.

Initial Brute‑Force Approach (Wrong Logic)

vector v = {1, 2, 3, 4, 1, 2};
int t = INT_MAX;

for (int i = 0; i = j) {
    t = v[j];   // ❌ wrong comparison & assignment
}

cout = j mixes a value with an index, leading to incorrect results.

Corrected Brute‑Force Solution (Index‑Based Thinking)

After rethinking the problem, the goal is to track the smallest index of a repeating element, not the value itself.

vector v = {1, 2, 3, 4, 1, 2};
int t = INT_MAX;

for (int i = 0; i  i) {
    t = i;   // ✅ store first occurrence index
}
vector v = {4, 5, 6, 7, 5, 4, 7};
vector freq(100, 0);
int t = INT_MAX;

for (int x : v) {
    if (freq[x] > 0) {
        t = x;
        break;
    }
    freq[x]++;
}

cout << t;

Complexity

  • Time: O(n)
  • Space: O(k) where k is the range of possible values (here 100).

Try It Yourself (Using unordered_map)

Before looking at any solution, attempt to solve the problem using std::unordered_map to track first occurrences.

Key Learning (Most Important)

The mistake wasn’t a syntax error—it was a misinterpretation of the problem statement.

  • Always clarify what “first” means in the context of the task.
  • Index‑based thinking is crucial for problems involving order.

Final Takeaway

The initial solution, though incorrect, helped highlight the importance of correctly interpreting requirements. Fixing your own logic is one of the strongest ways to improve problem‑solving skills.

Back to Blog

Related posts

Read more »

[BOJ/C++] 단계별로 풀어보기 - 브루트 포스

2026.01.08일차 입니다. 브루트 포스 풀어보았습니다. 브루트 포스Brute Force란 무차별 대입이라고도 부르며 모든 경우의 수를 대입하여 답을 찾는 방법입니다. 2798번 블랙잭 문제 링크 NC3 문제이므로 세 개의 반복문을 통해 구현해야 합니다. cpp include usi...

Kth Largest Element in C++

🧩 Problem Statement Given an array and an integer k, find the k‑th largest element. Example - Input: 3, 2, 1, 5, 6, 4, k = 2 - Output: 5 🧠 My First Thought:...