Data Structures19 sections · 729 units
Open in Course

Two Sum - Implementation

Complete solution

Here's the solution:

function twoSum(nums, target)
    indexMap := empty hash map  // value -> index

    for i from 0 to length of nums - 1
        complement := target - nums[i]

        if complement in indexMap
            return [indexMap[complement], i]

        indexMap[nums[i]] := i

    return []  // no solution (won't happen per problem)

Time: O(n)O(n). Space: O(n)O(n).