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
No sound? Captions are on by default.
3 · Now you drive
Keys:←→ stepSpace playR reset
Two Sum
or try
2–8 whole numbers from -99 to 99, then | and the target.Start with an empty map. It will remember each number’s index.Step 1 of 6. Starting out. 4 numbers to read, target 9. The map is empty.
Step 1 of 6
solution.ts▶ marks the line running now
function twoSum(nums: number[], target: number): number[] {
const seen = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen.has(need)) {
return [seen.get(need)!, i];
}
seen.set(nums[i], i);
}
return [];
}
4 · Your turn
0 of 8 problems solved
- Easy01
Contains Duplicate
Warm-up: one set remembers every number you have seen.
- Easy02
Valid Anagram
Warm-up: count the letters here, count them there, compare.
- Easy03
Two Sum
The one you just watched. Write it from memory.
- Medium04
Group Anagrams
Same letter counts, now used as a key for each group.
- Medium05
Top K Frequent Elements
Count everything first, then keep the k biggest counts.
- Medium06
Encode and Decode Strings
LeetCode PremiumStore each length up front, so decoding never guesses.
- Medium07
Product of Array Except Self
Prefix and suffix products, with no division allowed.
- Medium08
Longest Consecutive Sequence
A set finds each run’s start in constant time.