DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

First Repeating Element in an Array (C++)

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

While solving the first repeating element problem, I initially wrote a brute-force solution using nested loops.
At first glance, it looked correct — but it actually had a logical flaw.

This article explains:

  1. what went wrong
  2. how I corrected it
  3. what I learned about problem interpretation

📌 Problem Clarification (Very Important)

The task is to find:

The element whose first occurrence index is smallest among all repeating elements

Not:

the smallest value. Not just any duplicate. Order matters.

Initial Brute-Force Approach (Wrong Logic)

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

for (int i = 0; i < v.size(); i++) {
    for (int j = i + 1; j < v.size(); j++) {
        if (v[i] == v[j] && t >= j) {
            t = v[j];   // ❌ wrong comparison & assignment
        }
    }
}
cout << t;

Enter fullscreen mode Exit fullscreen mode

❌ Why This Is Wrong

t stores a value, not an index . Comparison t >= j mixes value vs index
You lose track of which occurrence comes first. So even though the code compiles, the logic is incorrect.

✅ Corrected Brute-Force Solution (Index-Based Thinking)

After rethinking the problem, I realized:

To find the first repeating element, I must track the smallest index, not the value.

Fixed Code

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

for (int i = 0; i < v.size(); i++) {
    for (int j = i + 1; j < v.size(); j++) {
        if (v[i] == v[j] && t > i) {
            t = i;   // ✅ store first occurrence index
        }
    }
}

cout << v[t];

Enter fullscreen mode Exit fullscreen mode

Complexity

Time: O(n²)
Space: O(1)

✔ Correct
✔ No extra space
❌ Slow for large inputs

🚀 Optimized Approach Using Frequency Array

vector<int> v = {4, 5, 6, 7, 5, 4, 7};
vector<int> freq(100, 0);
int t = INT_MAX;

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

cout << t;

Enter fullscreen mode Exit fullscreen mode

Complexity

Time: O(n)
Space: O(k) (range size)

✔ Fast
✔ Clear intent
❌ Uses extra space

🧪 Try It Yourself (Using unordered_map)

Before looking at any solution, try solving this problem using unordered_map.

🧠 Key Learning (Most Important)

The mistake wasn’t syntax — it was problem interpretation.

What I learned:

Always clarify what “first” means
Track indices, not just values
Correctness comes before optimization
A wrong idea + correction = real learning

🎯Final Takeaway

My first solution wasn’t useless — it helped me understand why index-based thinking matters.

Fixing your own logic is one of the strongest ways to improve problem-solving skills.

That’s real progress.

Top comments (1)

Collapse
 
charles_kumar_30654e10958 profile image
Charles Kumar

This helps me very much @nithya_dharshiniofficial


📐 The 5-Step Algorithm Design Framework

┌─────────────────────────────────────────────┐
│  1. UNDERSTAND   → What exactly are we     │
│                    solving?                 │
├─────────────────────────────────────────────┤
│  2. EXPLORE      → Try simple examples     │
│                    by hand                  │
├─────────────────────────────────────────────┤
│  3. PATTERN      → What repeats? What      │
│                    changes?                 │
├─────────────────────────────────────────────┤
│  4. DESIGN       → Choose your approach    │
│                    & data structures        │
├─────────────────────────────────────────────┤
│  5. OPTIMIZE     → Refine time & space     │
│                    complexity               │
└─────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

I start by reading the problem carefully and contextually, then sketch simple examples visually with known patterns.

After identifying appropriate patterns, i design, run and optimize the solution.

Hopes this approach helps all 🎉