Two Sum

easy · hash map, arrays

Two Sum

Given an integer slice nums and an integer target, return two distinct zero-based indices whose original values add up to target. Any valid pair in either order is accepted.

If no such pair exists, return [-1, -1] in Go or (-1, -1) in Python.

Function signature

func TwoSum(nums []int, target int) [2]int

In Python, implement two_sum(nums, target).

Example

nums = [2, 7, 11, 15]
target = 9
output = [0, 1]

Constraints

  • 2 <= len(nums) <= 200_000
  • -1_000_000_000 <= nums[i] <= 1_000_000_000

Aim for expected O(n) time.

Try it before coding

For [2,9,2] and target 4, which positions can serve as witnesses? Could a set of distinct input values alone tell you whether two positions exist?

Check your reasoning

Indices 0 and 2 are distinct and hold the two 2s. A set built from the whole input looks identical for [2,9], which has no pair.

Run tests to see results
No issues detected
    Join Discord