⚡ daily LC #1 · Easy
111 words
1 minute

Two Sum — hash map in one pass

Intuition#

Instead of checking every pair (O(n²)), remember what we’ve seen. For each number x, the complement we need is target - x. If we already saw it, we’re done.

Go#

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

Trap#

  • Don’t put seen[x] = i before the lookup. You’d match x + x = target against itself with the same index.
  • Guaranteed exactly one solution — so no “best pair” logic needed.

Complexity#

  • Time: O(n) — one pass, map ops are amortized O(1)
  • Space: O(n) — worst case we store every element
Two Sum — hash map in one pass
https://fuwari.vercel.app/posts/daily-two-sum/
Author
Thomas Engineer
Published at
2026-04-20
License
CC BY-NC-SA 4.0