First Repeating Element in an Array (C++)
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.