Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 15 minutesNeeds: arrays, hash mapsTime O(n)Space O(n)

2 · Watch

Arrays & Hashing in 60 seconds

Which two numbers add to 9? Checking every pair, the answer only turns up on the tenth and last try. That is n² work.

3 · Now you drive

Keys:←→ stepSpace playR resetHomeEnd jump

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 12. Starting out. 5 numbers to read, target 9. The map is empty.
Step 1 of 12
solution.ts
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 [];
}
▶ marks the line running now

4 · Your turn

0 of 8 problems solved

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.
  1. Easy01

    Contains Duplicate

    LeetCode 217 · Blind 75 · NeetCode 150

    Warm-up: one set remembers every number you have seen.

  2. Easy02

    Valid Anagram

    LeetCode 242 · Blind 75 · NeetCode 150

    Warm-up: count the letters here, count them there, compare.

  3. Easy03

    Two Sum

    LeetCode 1 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  4. Medium04

    Group Anagrams

    LeetCode 49 · Blind 75 · NeetCode 150

    Same letter counts, now used as a key for each group.

  5. Medium05

    Top K Frequent Elements

    LeetCode 347 · Blind 75 · NeetCode 150

    Count everything first, then keep the k biggest counts.

  6. Medium06

    Encode and Decode Strings

    LeetCode 271 · Blind 75 · NeetCode 150

    LeetCode Premium

    Store each length up front, so decoding never guesses.

  7. Medium07

    Product of Array Except Self

    LeetCode 238 · Blind 75 · NeetCode 150

    Prefix and suffix products, with no division allowed.

  8. Medium08

    Longest Consecutive Sequence

    LeetCode 128 · Blind 75 · NeetCode 150

    A set finds each run’s start in constant time.

UP NEXT · LESSON 2 OF 20Two PointersTwo indices walking toward an answer.