Hashing

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Store seen values in a hash map and look for the complement of each value.

Step 1 / 5
Problem shape
Current lesson

Two Sum Lab

Hashing Beginner

Two Sum

Welcome to the Two Sum algorithm lab. Store seen values in a hash map and look for the complement of each value. Use it when: Use when you need a pair that adds to a target and values are not necessarily sorted. The time complexity is O(n), and the space complexity is O(n). The pseudocode is: seen = empty map for i from 0 to n - 1 need = target - a[i] if need in seen return [seen[need], i] seen[a[i]] = i As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n)

Space

O(n)

Pseudocode

seen = empty map
for i from 0 to n - 1
  need = target - a[i]
  if need in seen return [seen[need], i]
  seen[a[i]] = i
Open deeper structure lesson
1.0x