Data Structures19 sections · 729 units
Open in Course

Two Sum - Algorithm

One pass solution

Use a hash map from value to index:

1.1. For each index ii with value nums[i]nums[i]:

  • Compute complement=targetnums[i]complement = target - nums[i]
  • If complementcomplement is in the map, return [map[complement],i][map[complement], i]
  • Otherwise, add nums[i]inums[i] \to i to the map

2.2. If no pair found, return empty (but problem guarantees a solution exists). One pass through the array. Each element is checked and added once. Time: O(n)O(n). Space: O(n)O(n).