Facebook Pixel

How to Optimize a Nested Loop into a Single Loop

A practical guide demonstrating exactly how to refactor an inefficient O(n^2) nested loop into an optimal O(n) single loop using Hash Maps.

Flattening the Curve

To understand how to optimize a nested loop, we must look at a practical example. Let's solve the most famous interview question: Two Sum. Given an array of integers and a target sum, find if any two numbers add up to the target.

The O(N^2) Nested Loop Approach

The brute force logic checks every possible pair.

for (int i = 0; i < nums.length; i++) {
    for (int j = i + 1; j < nums.length; j++) {
        if (nums[i] + nums[j] == target) return true;
    }
}

The inner loop's entire job is to scan the future elements searching for the complement: (target - nums[i]).

The Optimization Strategy

Instead of looking forward with an inner loop, what if we look backward using memory? As we iterate, we can store every number we see in a Hash Set. At every step, we check the Set to see if our required complement is already in there. Hash Set lookups are instant (O(1)).

The O(N) Single Loop Approach

HashSet<Integer> seen = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
    int complement = target - nums[i];
    
    // O(1) lookup completely replaces the inner loop!
    if (seen.contains(complement)) {
        return true;
    }
    
    // Remember this number for future iterations
    seen.add(nums[i]);
}

The Result

We completely eliminated the inner loop. The algorithm now passes through the array exactly once. We traded O(1) space for O(N) space (the Hash Set), but we improved the speed from O(N^2) to O(N).

The Takeaway

Whenever an inner loop is simply searching for a value, it can almost always be deleted and replaced with an O(1) Hash Set or Hash Map lookup.

The most common way is to eliminate the inner loop by utilizing a Hash Map or Hash Set to store and retrieve data in O(1) constant time.

The complement is the exact value needed to reach the target sum. It is calculated by subtracting the current number from the target (Target - Current).

An inner loop takes O(N) time to scan an array for a value. A Hash Set takes O(1) time to check if it contains a value, making it massively faster.

You trade Space for Time. The single loop is incredibly fast (O(N)), but you must consume extra memory (O(N)) to build the Hash Set.

No. It only works if the inner loop's purpose is searching or counting. It does not work if the inner loop is printing a 2D matrix or sorting data.

Please Login.
Please Login.
Please Login.
Please Login.