Most frequent element — watch the pointers move
The same brute-force logic as before, now animated: two colored pointers slide across the array as i and j advance, a beam lights up teal on a match and rose on a mismatch, and the counters pop the instant they change.
01 The code being traced
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[j] == arr[i]) {
count++;
} else if (maxCount < count) {
maxCount = count;
element = arr[i];
}
}
}
System.out.print(element);
02 Live pointer tracer
Amber pointer = i. Teal pointer = j. The beam between them turns teal on a match, rose on a mismatch — watch how often it stays rose right before the answer should update.
03 Every comparison, in order
Click any row to jump the tracer above straight to that comparison. Rows in rose are where the inner loop ends on a match — the exact moment a real update gets skipped.
| # | i | j | arr[i] | arr[j] | Branch | count | maxCount | element |
|---|
maxCount only runs inside the else if branch — triggered by a mismatch. Whenever the inner loop's last tick happens to be a match, that final count is never checked, and maxCount silently stays behind the true frequency.
04 Complexity
| Metric | Value |
|---|---|
| Time | O(n²) — for every i, scan all j |
| Space | O(1) extra — no hash array, no auxiliary storage |
The "comparisons so far" counter above grows exactly like the progress bar suggests — every extra element added to the array multiplies the remaining work, not just adds to it.
05 Quick revision
Two nested loops, zero extra memory
i is the candidate value, j re-scans the whole array to count its occurrences.
element = arr[i], not i
The winner stores the actual repeated value, never the index it was found at.
The update lives in the mismatch branch
maxCount only changes inside else if — a match alone never triggers it.
Last-tick matches get skipped
If j's final tick is a match, that count has no mismatch left to compare it.
Trace before you trust
Any array where the true mode sits at the end (like [1, 2, 2]) exposes the bug immediately.
The fix: compare once per i, after j finishes
Moving the check outside the inner loop guarantees every count gets compared exactly once.
Comments
Post a Comment