DevPath

← All problems

Two Sum

Easy arrays · hashing

Description

Return the indices i < j of the two numbers that add up to target. Exactly one solution exists.

Constraints

2 <= n <= 100000; exactly one valid answer

Examples

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

2 + 7 = 9

Hints (1)
  • Store each value with its index as you go; look for target - value.

Solutions

One pass with a value -> index map. · Time O(n) · Space O(n)

func twoSum(nums []int, target int) []int {
    seen := map[int]int{}
    for i, n := range nums {
        if j, ok := seen[target-n]; ok {
            return []int{j, i}
        }
        seen[n] = i
    }
    return []int{}
}

Create a free account to submit solutions, track progress and save problems.

Create account