The brute-force solution checks every possible pair of numbers, leading to:
The optimal solution uses a hash map to achieve O(n) time complexity:
The “Two Sum” problem is one of the most well-known algorithmic challenges. Given an array of integers nums
and an integer target
, the task is to find the indices of two distinct numbers in nums
such that they add up to target
.
For example:
nums = [2, 7, 11, 15]
, target = 9
→ Output: [0, 1]
because 2 + 7 = 9
.nums = [3, 2, 4]
, target = 6
→ Output: [1, 2]
Two Sum introduces fundamental concepts in problem solving: iteration, complement computation, and the power of hash maps for constant-time lookup. It also forms the basis for more complex variations like Three Sum, Four Sum, and problems involving pairs with constraints.
The most straightforward solution is to use two nested loops to check every pair of numbers. For each element nums[i]
, we scan the remaining elements to find if any nums[j]
satisfies nums[i] + nums[j] == target
.
While easy to implement, this method performs poorly on large arrays due to its quadratic time complexity.
i
from 0 to n - 1.j
from i + 1 to n - 1.nums[i] + nums[j] == target
, return [i, j]
.null
.
A more efficient solution uses a hash map to store previously seen numbers and their indices.
As we iterate through the array, we calculate the complement target - nums[i]
and check if it's already in the map.
If it is, we return the current index and the stored index of the complement.
seen = {}
.i
and value num
.complement = target - num
.complement
exists in seen
, return [seen[complement], i]
.seen[num] = i
.
Input: nums = [3, 2, 4]
, target = 6
Iteration:
Time Complexity: O(n), where n is the length of the array. We loop through the array once, and hash map lookups and inserts are constant time.
Space Complexity: O(n), for storing up to n elements in the map.
[]
or throw an error depending on the implementationThe “Two Sum” problem is a great introduction to using hash maps to speed up lookups and eliminate redundant comparisons. Understanding this approach is key to tackling more advanced problems involving combinations, subsets, or real-time aggregation.