Math Fundamentals18 sections · 814 units
Open in Course

Two Sum - Implementation

In pseudocode

Here's the solution:


function twoSum(nums, target)
    map := empty hash map
    for i from 0 to length of nums - 1
        complement := target - nums[i]
        if complement exists in map then
            return [map[complement], i]
        map[nums[i]] := i
    return []

The map stores values as keys and indices as values. When you find the complement, return both indices immediately.