intro practice · coding problem

Two Sum with a hash map

Given an array of integers and a target, return the indices of the two numbers that add to the target. Solve it in a single pass.

The mechanism

A hash map trades memory for time: it turns an O(n) scan for "have I seen this?" into an O(1) lookup. Most array problems that feel quadratic collapse to linear once you ask what you would store in a map keyed by value, complement, or frequency.

Study Arrays & Hashing

Expected evidence

twoSum([2,7,11,15], 9) -> [0,1]

Try this drill in the practice workspace →

Hints when you need them
  • For each number, what value would complete the pair?
  • Store value -> index as you scan; check for the complement before inserting.

Watch for these mistakes

  • Reaching for nested loops before asking "what would a hash map key on?"
  • Mutating a collection while iterating it
  • Forgetting hash maps have no order — sort separately if order matters

Check the sources

Practice the same mechanism

Browse all practice briefs