Typorithm · easy

Two Sum

two-sumarrays-hashinghash-mapcomplementone-pass
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Two Sum

0%

Arrays & Hashing

Store each value's index in a Map; for each number, check if its complement was already seen.

The brute-force pair check is O(n^2); hashing trades a little memory for O(n) time.

For each number, its complement is target minus itself.

If that complement is already in the Map, the answer is its stored index and the current one.

01

Map stores value → index.

02

Check the complement first, then store.

03

One pass, O(n) time.

function twoSum(nums, target) {
  const seen = new Map();

  for (let i = 0; i < nums.length; i += 1) {
    const need = target - nums[i];

    if (seen.has(need)) {
      return [seen.get(need), i];
    }

    seen.set(nums[i], i);
  }

  return [];
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Value → index map

A Map remembers each value's index for O(1) lookup.

const seen = new Map()

2. Complement

The partner value that would complete the target sum.

const need = target - nums[i]

3. Seen the partner?

If the complement was stored earlier, the pair is found.

if (seen.has(need))

4. Remember value

Store the current value and index for future complements.

seen.set(nums[i], i)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Two Sum: Lesson & Practice · Typorithm | ApplyDjinn