#1

Two Sum

Easy HashMap complement lookup

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the indexes of the two numbers that add up to target. Exactly one answer exists and the same element can't be used twice.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: two indexes whose values add up to target.

Why this works: for each number x, the partner you need is target - x. A map from value to index answers "have I seen it?" in O(1).

Example: [2, 7, 11, 15], target 9

2: need 7, not seen; store 2→07: need 2, seen at 0 → [0, 1]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Inserting x first and then looking up target − x, which can return the same index twice when x = target / 2.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Hashing
🎬 Episodes 37–39: video coming soon