Skip to main content
Back to all problems
Beginner guide, Algorithms & data structures

Arrays & Hashing

The starting point: a hash map or set turns an O(n) search into O(1). Almost every later topic leans on this.

Most problems in this category come down to one question: "have I seen this before?" This guide explains the two tools that answer it instantly, the hash set and the hash map, and the four patterns you'll use them for again and again.

First, a 60-second intro to "Big O"

Interviewers describe speed with Big O notation. It answers: if the input gets bigger, how much more work does my code do? n is the size of the input (for example, the length of the array).

NotationIn plain wordsExample
O(1)Same work no matter how big the input isLooking up a word in a hash map
O(n)Look at each item about onceOne loop over the array
O(n log n)A bit more than once per itemSorting
O(n²)Compare every item with every other itemA loop inside a loop over the same array

For 100,000 items, O(n) is about 100,000 steps, while O(n²) is about 10,000,000,000. That gap is why the problems here ask you to avoid nested loops.

The problem: searching a list is slow

Say you're walking through an array and want to know whether you've seen the value 42 already. If you keep the seen values in a plain array, you have to check them one by one. Do that for every item, and you have a loop inside a loop: O(n²).

We need a collection that answers "is 42 in here?" without looking at everything.

The hash set: a guest list

Picture the guest list at a party, sorted into 26 drawers by the first letter of each name. To check whether "Dana" is invited, you don't read the whole list. You open the D drawer and look at the few names inside.

A hash set works the same way, just smarter. A hash function turns any value into a drawer number (a bucket). To add a value or check for it, the set computes the drawer number and goes straight there.

Loading diagram...

Because the computer jumps straight to the right bucket, adding and checking take O(1) on average, no matter how many values are stored.

js
const seen = new Set()
seen.add(42) // add a value
seen.has(42) // true: is it in here?
seen.has(7) // false
seen.delete(42) // remove it
seen.size // how many values are stored
python
seen = set()
seen.add(42)      # add a value
42 in seen        # True: is it in here?
7 in seen         # False
seen.remove(42)   # remove it
len(seen)         # how many values are stored

A set stores each value once: adding 42 twice still leaves one 42.

The hash map: a coat check

A hash set only remembers whether a value is there. Often you also need to remember something about it: how many times you've seen it, or where you saw it.

A hash map (also called a dictionary) is like a coat check: you hand over a ticket number (the key) and get back your coat (the value). It uses the same bucket trick on the key, so looking up a key is also O(1) on average.

js
const ages = new Map()
ages.set('dana', 30) // store key -> value
ages.get('dana') // 30
ages.has('dana') // true
ages.get('omer') // undefined: not stored
python
ages = {}
ages["dana"] = 30   # store key -> value
ages["dana"]        # 30
"dana" in ages      # True
ages.get("omer")    # None: not stored

Tip

In JavaScript, prefer Map and Set over plain objects ({}) for these problems. A Map can use numbers as keys without turning them into strings, keeps insertion order, and has a size.

The trade-off: memory for speed

A set or map uses extra memory, up to one entry per item: O(n) space. In exchange, you usually turn an O(n²) solution into O(n). In interviews, that's almost always a trade worth making, and you should say it out loud: "I'm using O(n) extra memory to get O(n) time."

The four patterns

1. "Have I seen it?" (hash set)

Walk the array once. For each item, check first, then add.

js
const seen = new Set()
for (const x of nums) {
  if (seen.has(x)) {
    // x appeared before
  }
  seen.add(x)
}

Used in: Contains Duplicate, Longest Consecutive Sequence.

2. Counting (hash map: item → count)

Build a tally of how many times each item appears.

js
const counts = new Map()
for (const x of items) {
  counts.set(x, (counts.get(x) ?? 0) + 1)
}

Used in: Valid Anagram, Top K Frequent Elements.

3. "Where did I see it?" (hash map: value → index)

When you need positions, store the index along with the value.

js
const indexOf = new Map()
for (let i = 0; i < nums.length; i++) {
  // look something up in indexOf first...
  indexOf.set(nums[i], i)
}

Used in: Two Sum.

4. Grouping (hash map: key → list)

Compute a key for each item so that items that belong together share the same key, then collect them in lists.

js
const groups = new Map()
for (const item of items) {
  const key = makeKey(item)
  if (!groups.has(key)) groups.set(key, [])
  groups.get(key).push(item)
}
const result = [...groups.values()]

Used in: Group Anagrams.

How to recognize this category

Reach for a set or map when the problem mentions:

  • duplicates, unique, or distinct values
  • counting, frequency, or "most common"
  • finding a pair that adds up to something
  • grouping things that are "the same" in some way
  • an unsorted array and a requirement of O(n) time (so sorting is not allowed)

Common mistakes

  • Adding before checking. In pattern 1 and 3, if you add the current item first, it will "find itself".
  • Using an array or object as a Map key in JavaScript. Two arrays with the same contents are different objects, so the lookup fails. Turn the key into a string first, e.g. counts.join(',').
  • Forgetting that order is lost. A set doesn't remember positions or how many times you added something. If you need either, use a map.

A few problems here need an extra trick

Some problems in this category use a hash map plus one more idea. Each one teaches its trick in its own solution, step by step:

  • Top K Frequent Elements: bucket sort (using counts as array positions).
  • Product of Array Except Self: prefix and suffix products (running totals from the left and right).
  • Encode and Decode Strings: length-prefixing (announcing a string's length before it).

Practice what you learned

The problems go from easier to harder. Try each one on your own and open a hint when you get stuck.