How to use hash maps in coding interviews

Learn to recognize when a hash map replaces repeated searches, choose what it stores, and prove your solution with a few small examples.

Start with the lookup you keep repeating

A hash map stores values under keys. In Python, a dictionary lets you ask whether a key is present, retrieve its value, or update it. If your first solution scans a list over and over to find one value, count an item, or collect matching records, ask what information would let you replace that scan with a lookup.

The useful design decision is what goes on each side of the map. Use the thing you search for as the key. Store the smallest piece of information that lets you produce the answer. A set is enough for membership alone. A dictionary can also remember a position, a count, or a group of records.

Choose the value to match the answer

Consider the target-pair problem. For each number x, we need an earlier number equal to target − x. That makes the earlier number the key. Because the caller needs positions, the value is the index where we saw that number. If the caller only asked whether any pair exists, a set of earlier numbers would be enough.

At index 0 of [3, 3] with target 6, we look for 3 in an empty dictionary. We then store 3 with index 0. At index 1, the same lookup returns 0. Checking before storing keeps the current position out of the candidates. Reversing those steps makes [3] incorrectly match itself.

Say the invariant out loud in an interview: before handling index i, the map contains earlier values and one valid position for each. Whenever a pair exists, the iteration for its later index can find the earlier value. One position per value is enough because the problem accepts any valid pair.

def target_pair(values, target):
    seen = {}
    for i, value in enumerate(values):
        need = target - value
        if need in seen:
            return seen[need], i
        seen[value] = i
    return None

assert target_pair([3, 3], 6) == (0, 1)
assert target_pair([3], 6) is None
assert target_pair([-2, 0, 4], 2) == (0, 2)
assert target_pair([], 9) is None
print('4 checks passed')

The same idea can count or group

If the question becomes “How many distinct index pairs add to the target?”, one earlier index per value no longer works. For [3, 3, 3] and target 6, the second 3 contributes one pair and the third contributes two. Store earlier occurrence counts. Each iteration adds the number of earlier complements, so every pair is counted at its later position.

For grouping, use a shared attribute as the key and append each record to the corresponding list. For example, grouping tickets by status needs the status as the key and a list of ticket IDs as the value. In both examples, the requested output tells you what to store.

def count_pairs(values, target):
    counts = {}
    total = 0
    for value in values:
        total += counts.get(target - value, 0)
        counts[value] = counts.get(value, 0) + 1
    return total


def group_ticket_ids(tickets):
    by_status = {}
    for ticket_id, status in tickets:
        by_status.setdefault(status, []).append(ticket_id)
    return by_status


assert count_pairs([3, 3, 3], 6) == 3
assert count_pairs([1, 4, 1, 4], 5) == 4
assert count_pairs([3], 6) == 0
assert group_ticket_ids([(7, 'open'), (8, 'closed'), (9, 'open')]) == {
    'open': [7, 9], 'closed': [8],
}

What the time and space claims assume

Checking every pair costs O(n²) time and uses O(1) extra space. The dictionary scan does a constant number of lookups and updates per input item. For ordinary integer keys, those operations are expected to take constant time, with resizing costs spread across inserts. The scan therefore takes expected O(n) time and uses O(n) extra space in the worst case for space, when all values are different.

A hash maps a key to a number that helps the table locate candidate entries. Different keys can land in the same place, so the table still checks equality. Heavy collisions or expensive key hashing can change the lookup cost. If the key is a long string or a tuple, account for the cost of constructing and hashing it when that matters to the problem.

If the input is already sorted, two pointers can find a target pair in O(n) time with O(1) extra space. Start at the ends. If the sum is too low, move the left pointer. If the sum is too high, move the right pointer. Sorting an unsorted list first generally adds O(n log n) work, and you must carry original positions if the answer asks for them.

Use the contract to pick your tests

Start with duplicates, no solution, negative numbers, and an empty list. If a question promises one solution, check that assumption with the interviewer before you rely on it. If it asks for the earliest pair or all pairs, say how that changes the state and the returned answer.

Try one variation: given a stream of user IDs, report the first ID that appears twice. What is the smallest state you can keep? Membership is all you need when reporting the ID. If the caller also wants the position of its first appearance, store that position as the value. That choice is the part of the target-pair solution you can reuse.

The team guide · My original notes on testing coding agents · Working with Lightbulb Partners