Common Mistakes When Initializing the Inner Loop Counter
Identify the critical off-by-one errors and reset bugs that occur when declaring and initializing the inner loop counter.
The Inner Reset
Because nested loops have multiple moving parts, initialization bugs are extremely common. A slight misconfiguration of the inner loop's starting point completely breaks combinatorial algorithms.
Mistake 1: Starting at 0 Instead of i + 1
When generating unique pairs from an array (e.g., Two Sum without repeats), the inner loop must start at j = i + 1.
If you incorrectly start at j = 0:
- The inner loop evaluates elements the outer loop already processed.
- The inner loop evaluates the exact same element against itself when
i == j. This creates redundant duplicate pairs and breaks combinations.
Mistake 2: Starting at i Instead of i + 1
Sometimes candidates realize they shouldn't start at 0, so they write:
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) // Bug!
Starting at i means the very first execution of the inner loop compares arr[i] against arr[j] where both are at the same index. You are pairing an item with itself. The inner loop must always start at the next element: j = i + 1.
Mistake 3: Global Counter Declarations
In older languages (like C) or poorly written JS, developers sometimes declare loop variables globally.
int j;
for (int i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) { ... }
}
If you forget to reset j = 0 on subsequent loops, or if another function modifies j, the inner loop will not execute. Always declare your counter strictly inside the loop initialization block: for (int j = 0...).
The Takeaway
The starting condition of the inner loop determines the mathematical behavior of the entire algorithm. If traversing a grid, start at 0. If generating combinations, start at i + 1.
When generating unique pairs, starting at i + 1 ensures the loop only looks forward, preventing self-pairing and avoiding duplicate mirrored pairs.
It should start at 0 when you are traversing multi-dimensional data, like a 2D matrix, where every row requires processing from the very first column.
The algorithm will pair the current element with itself on the first inner iteration. If summing elements, it will incorrectly add the same element twice.
Declaring variables directly inside the for loop definition (e.g., int j = 0) ensures they are reset properly and prevents interference from other parts of the program.
If the inner loop starts at i + 1, the outer loop must stop at length - 1, otherwise on the last iteration, i + 1 will cause an Index Out of Bounds error.
