Skip to content
Visual explainer 5h to learn 5 steps

Hash maps & sets

Use hashing to turn O(n²) into O(n).

By Invicly Tech, , in Interview Preparation. About 10 minutes to read.

Topic 3 of 27

In short

Hash maps and sets give average O(1) insert and lookup. Replacing an inner search loop with a hash lookup is the classic way to turn O(n squared) into O(n).

Explained simply

A hash map is like a coat check with numbered hooks. You give it a key, such as a word, and a maths function turns that key into a hook number. To find the value again, it runs the same function and goes straight to that hook. No searching through every coat.

That is why hash maps feel like magic in interviews. Whenever your code says "for each item, search the whole array for something", you can usually store what you have seen in a map or set and replace the search with one lookup. The slow inner loop disappears.

Use a set when you only care whether something exists. Use a map when you need to remember something about it: its count, its index, or a list of related items. The price is memory, since you may store up to n extra entries.

The real skill interviewers test is choosing the key. For anagrams the key is the sorted letters. For "pairs that add up to a target" the key is the number you still need. Once the key is right, the code is usually short.

Press Play on a diagram to walk through it one step at a time.

FlowHow a hash map finds a key
  1. Step 1
    Hash the key

    hash('cat') gives a large integer

  2. Step 2
    Pick a bucket

    index = hash mod number of buckets

  3. Step 3
    Scan the bucket

    Compare keys with equals to find a match

  4. Step 4
    Resize when full

    Past the load factor, double and rehash

CompareTwo Sum approaches
Brute force
  • Check every pair
  • O(n squared) time
  • O(1) extra space
Hash map
  • Store value to index
  • Look up target minus x
  • O(n) time, O(n) space
CompareSet, map or an array of counts?
HashSet
  • Answers: have I seen x?
  • Contains Duplicate, visited checks
  • O(1) average add and contains
HashMap
  • Answers: what do I know about x?
  • Two Sum, frequencies, grouping
  • O(1) average get and put
int[26] counts
  • Keys are letters or small integers
  • Anagrams, Ransom Note
  • Fastest, fixed O(1) space

In depth

Pick the key, then the value

Before writing code, ask: what question will I ask the map later? The thing you will know at that moment is the key, and the answer you want back is the value.

In Two Sum, at index i you know x and need to ask "where is target - x?", so the key is a number and the value is its index. In Group Anagrams you know a word and ask "which group does it belong to?", so the key is a canonical form of the word and the value is a list. In a frequency problem the key is the item and the value is its count.

  • Membership only: Set
  • Counting: Map item to count
  • Positions: Map value to index
  • Grouping: Map canonical key to list

Longest Consecutive Sequence in O(n)

Given unsorted numbers, find the longest run of consecutive values like 1, 2, 3, 4. Sorting gives O(n log n). The hash set trick: put everything in a set, then only start counting from numbers that begin a run, meaning x - 1 is not in the set. From each start, walk x + 1, x + 2 and so on while they exist.

It looks like a nested loop, but each number is visited by an inner walk at most once, because only run starts launch a walk. Total work is O(n) time with O(n) space for the set.

FlowLongest run in [100, 4, 200, 1, 3, 2]
  1. 1
    Build a set

    All six numbers

  2. 2
    100 and 200

    99 and 199 missing: runs of 1

  3. 3
    4, 3, 2

    x - 1 is present: not a start, skip

  4. 4
    1

    0 missing: walk 2, 3, 4

  5. 5
    Answer: 4

    Each number walked at most once: O(n)

Counting idioms in Java

Counting is the most common map job, so learn the short forms. map.merge(key, 1, Integer::sum) adds one and creates the entry if it is missing. map.getOrDefault(key, 0) reads a count safely. map.computeIfAbsent(key, k -> new ArrayList<>()).add(item) builds groups in one line.

If keys are lowercase letters, an int[26] array is faster and avoids boxing, which is Java wrapping each int in an Integer object. Two words are anagrams when their 26 counts match, which takes O(n) instead of sorting in O(n log n).

When hashing is the wrong tool

Hash maps do not keep order. If you need the smallest key, a range of keys, or sorted output, use a TreeMap with O(log n) operations, or sort instead. If memory is tight and the array is already sorted, two pointers may give O(1) space.

Also remember the worst case. If many keys collide, lookups slow toward O(n). Since Java 8, HashMap turns long bucket chains into small balanced trees, so the worst case becomes about O(log n) for comparable keys. In an interview, "O(1) average" is the precise wording.

CompareHashMap vs TreeMap in Java
HashMap
  • get and put: O(1) average
  • No key order
  • Long buckets become trees since Java 8
TreeMap
  • get and put: O(log n)
  • Keys kept sorted
  • firstKey, floorKey, subMap for ranges

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Learn how hash maps work internally~1h
  2. 2
    Count frequencies with maps~1h
  3. 3
    Use sets for membership checks~1h
  4. 4
    Practice: Group Anagrams, Contains Duplicate~1h
  5. 5
    Practice: Longest Consecutive Sequence~1h

Key points

  • Average O(1) operations; worst case O(n) if many keys collide.
  • Use a map to count frequencies and a set for fast membership checks.
  • A canonical key, like sorted letters, groups equivalent items such as anagrams.
  • Keys must be immutable: tuples work in Python, lists do not.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def two_sum(nums, target):
    seen = {}  # value -> index
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i
    return []

def group_anagrams(words):
    groups = {}
    for w in words:
        groups.setdefault(''.join(sorted(w)), []).append(w)
    return list(groups.values())

Longest Consecutive Sequence step by step

Input [100, 4, 200, 1, 3, 2]. The set holds all six values. 100: is 99 present? No, so it starts a run; 101 is missing, length 1. 4: 3 is present, so skip. 200: run of length 1. 1: 0 is missing, so start; walk 2, 3, 4, then 5 is missing: length 4. 3 and 2 are skipped. Answer 4. Each number is touched a constant number of times: O(n) time, O(n) space.

java
int longestConsecutive(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int x : nums) set.add(x);
    int best = 0;
    for (int x : set) {
        if (set.contains(x - 1)) continue;   // not a run start
        int len = 1;
        while (set.contains(x + len)) len++;
        best = Math.max(best, len);
    }
    return best;
}

First unique character in a string

For "leetcode", pass 1 counts letters: l = 1, e = 3, t = 1, c = 1, o = 1, d = 1. Pass 2 walks the string again and returns the first index whose count is 1, which is index 0 for 'l'. For "aabb" no letter has count 1, so return -1. Two passes over n characters give O(n) time, and the count array always has 26 slots, so space is O(1).

java
int firstUniqChar(String s) {
    int[] count = new int[26];
    for (char c : s.toCharArray()) count[c - 'a']++;
    for (int i = 0; i < s.length(); i++) {
        if (count[s.charAt(i) - 'a'] == 1) return i;
    }
    return -1;
}

Quick reference

  • HashSet: O(1) average add and contains. HashMap: O(1) average get and put.
  • Count: map.merge(k, 1, Integer::sum)
  • Group: map.computeIfAbsent(k, x -> new ArrayList<>()).add(v)
  • Letters only? Use int[26] with index c - 'a'.
  • Need order or ranges? TreeMap gives O(log n) per operation.
  • Prefix sum + map counts subarrays with sum k in O(n).
  • Say "O(1) average"; collisions make the worst case slower.

Common mistakes

  • Inserting x before checking target - x, which pairs an element with itself.
  • Using a mutable list as a dictionary key.
  • Forgetting the O(n) extra memory in the complexity answer.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In Longest Consecutive Sequence, why skip x when x - 1 is in the set?

Question 2

2Which structure answers "what is the smallest key greater than 50?" efficiently?

Question 3

3Checking whether two lowercase words are anagrams with int[26] counts costs:

Question 4

4What does map.merge(word, 1, Integer::sum) do?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Contains Duplicate: return true if any value appears at least twice in the array.

  2. Exercise 2medium

    Contains Duplicate II: return true if two equal values sit at indexes at most k apart.

  3. Exercise 3hard

    Top K Frequent Elements in O(n): return the k most frequent values without sorting all counts.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why is it O(1) if the map still has to compute a hash?
Computing the hash takes the same time no matter how many entries the map holds, so it is constant with respect to n. For string keys hashing depends on string length, which is usually treated as small.
Can I use an int array as a HashMap key in Java?
Not safely. Arrays use identity for equals and hashCode, so two arrays with the same contents are different keys. Convert to a String first, for example new String(sortedChars) or Arrays.toString(counts).
Is a HashMap or sorting better in an interview?
A HashMap usually gives better time, O(n) instead of O(n log n), but costs O(n) memory. Mention both and let the constraints decide.

Go deeper

ShareXLinkedInWhatsApp