Math Fundamentals18 sections · 814 units
Open in Course

Two Sum - Hash Map Approach

Efficient lookup

Use a hash map to store numbers you've seen. For each number xx, compute the complement targetxtarget - x and check if it's in the map.

If the complement exists, you found your pair. If not, add the current number to the map and continue.

This takes O(n)O(n) time with O(n)O(n) space. The brute force approach (checking all pairs) would take O(n2)O(n^2).