Arrays & Hashing
A coat check takes your coat and hands you a ticket. Later you show the ticket and your coat comes back at once, with nobody searching the rack. A hash map is the same trade: spend a little memory and every lookup is instant.
2 · Watch
Arrays & Hashing in 60 seconds
3 · Now you drive
Two Sum
4 · Your turn
Start from this
// Remember each number and where you saw it.
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
// What would pair with this number?
const key = wanted(nums[i]);
if (seen.has(key)) return [seen.get(key)!, i];
// Store after the check so it can't match itself.
seen.set(nums[i], i);
}Easy ways to go wrong
- Writing a nested loop before asking what you could store instead.
- Looking things up in a list, which costs O(n) every time.
- Using an array as a map key. Turn it into a string or tuple first.
- Easy01
Contains Duplicate
Warm-up: one set remembers every number you have seen.
You keep asking “have I seen this before?”, so keep a set.
- Time
- O(n)
- Space
- O(n)
- Easy02
Valid Anagram
Warm-up: count the letters here, count them there, compare.
Only the letter counts matter, so count and compare.
- Time
- O(n)
- Space
- O(1)
- Easy03
Two Sum
The one you just watched. Write it from memory.
Each number tells you exactly which partner it needs, so look the partner up.
- Time
- O(n)
- Space
- O(n)
- Medium04
Group Anagrams
Same letter counts, now used as a key for each group.
Words that belong together share a key: their sorted letters or letter counts.
- Time
- O(n·k)
- Space
- O(n·k)
- Medium05
Top K Frequent Elements
Count everything first, then keep the k biggest counts.
Count with a map, then bucket values by their count.
- Time
- O(n)
- Space
- O(n)
Also works with Heaps.
- Medium06
Encode and Decode Strings
LeetCode PremiumStore each length up front, so decoding never guesses.
Write each length first, so you never need a separator that could clash.
- Time
- O(n)
- Space
- O(n)
- Medium07
Product of Array Except Self
Prefix and suffix products, with no division allowed.
Everything to my left times everything to my right: two running products.
- Time
- O(n)
- Space
- O(1)
- Medium08
Longest Consecutive Sequence
A set finds each run’s start in constant time.
A set lets you count only from the true start of each run.
- Time
- O(n)
- Space
- O(n)