CodingPatterns8 min read

Hash Maps and Prefix Sums

A hash map trades memory for time: you remember what you have seen so that a later question ("have I seen the complement?", "how many times?", "where did this first appear?") costs O(1) on average instead of another scan. Prefix sums do the same for ranges: precompute running totals once and any range sum becomes a subtraction. Put the two together and you can answer questions about subarrays with negative numbers, which the sliding window cannot handle.

This lesson is for software engineering and data candidates preparing for a live coding round. It covers the three everyday uses of a map (lookup, counting, grouping), prefix sums, the prefix-count technique, and a worked example. Code is in Python.

When the pattern fits

  • You are about to write a nested loop to find a matching element. The inner loop is usually a lookup a map can do.

  • The problem is about frequencies: duplicates, anagrams, the most common item, the first unique one.

  • You need to group items that share a property: words with the same letters, transactions by account.

  • The problem asks about subarray sums and values can be negative, or you need many range sums.

The cost is O(n) extra memory. Say it when you propose the map; if the interviewer then asks for O(1) space, that is a signal to look at sorting with two pointers instead (see Two Pointers).

Use 1: lookup

The best-known example is finding two values that sum to a target: for each value, check whether its complement has already been seen, then record the value. That is one pass, O(n) time. The Coding Interviews lesson walks through it in full, so here is the general shape: ask the map about the past, then add the present. Doing it in that order is what prevents an element from matching itself.

A set is a map without values. "Find the longest run of consecutive integers in an unsorted array" is a good example of a set doing real work:

def longest_consecutive_run(nums):
    values = set(nums)
    best = 0
    for v in values:
        if v - 1 in values:
            continue              # not the start of a run
        length = 1
        while v + length in values:
            length += 1
        best = max(best, length)
    return best

Sorting would cost O(n log n). This is O(n): the inner loop only starts at the beginning of a run, so each value is visited by an inner loop at most once. For [100, 4, 200, 1, 3, 2] the run 1, 2, 3, 4 gives 4. Explaining why the nested loop is still linear is exactly the kind of reasoning the problem solving dimension rewards.

Use 2: counting

Python's Counter (or a map of value to count in any language) answers frequency questions directly:

  • Are two strings anagrams? Compare their letter counts. O(n), versus O(n log n) for sorting both.

  • First character that appears once: count in one pass, then scan the string again and return the first character with count 1. Two passes is still O(n).

  • Most frequent k items: count, then take the top k with a heap (see Heaps and Top K) or bucket by count.

Use 3: grouping

Pick a key that is identical for items that belong together, and map each key to a list.

from collections import defaultdict

def group_by_letters(words):
    groups = defaultdict(list)
    for word in words:
        key = "".join(sorted(word))
        groups[key].append(word)
    return list(groups.values())

"listen", "silent" and "enlist" all share the key "eilnst". Sorting each word costs O(m log m) for a word of length m. If the alphabet is fixed, a tuple of 26 letter counts is a key built in O(m). Keys must be immutable (hashable): tuples, not lists.

Prefix sums

Define prefix[i] as the sum of the first i elements, with prefix[0] = 0. Then the sum of nums[l..r] (inclusive) is prefix[r + 1] - prefix[l].

def build_prefix(nums):
    prefix = [0]
    for x in nums:
        prefix.append(prefix[-1] + x)
    return prefix

# sum of nums[2..4] == prefix[5] - prefix[2]

Building is O(n); each range query is then O(1). The extra leading zero is what makes ranges that start at index 0 work without a special case.

Prefix counts: subarrays that sum to k

Prompt: "Count the contiguous subarrays whose sum equals k. Values may be negative."

With negatives, a sliding window fails: shrinking might raise the sum. Instead, rephrase. A subarray ending at index i sums to k exactly when running_sum_at_i - running_sum_before_start == k, which means some earlier running sum equals running_sum_at_i - k. So walk the array once, and keep a map from each running sum to how many times it has occurred.

def count_subarrays_with_sum(nums, k):
    seen = {0: 1}          # the empty prefix
    running = 0
    count = 0
    for x in nums:
        running += x
        count += seen.get(running - k, 0)
        seen[running] = seen.get(running, 0) + 1
    return count

Trace [1, 2, 1, -1, 2] with k = 3:

  1. running 1: need -2, none. Seen {0: 1, 1: 1}.

  2. running 3: need 0, found once. Count 1 (the subarray 1, 2).

  3. running 4: need 1, found once. Count 2 (2, 1).

  4. running 3: need 0, found once. Count 3 (1, 2, 1, -1). Now 3 has been seen twice.

  5. running 5: need 2, none.

Answer: 3. The {0: 1} seed is the line people forget; without it, subarrays that start at index 0 are never counted. Time O(n), space O(n).

The same idea, with a remainder instead of a sum, counts subarrays whose sum is divisible by k: two prefixes with the same remainder bound a divisible subarray. In Python, % already returns a non-negative remainder for a positive k; in Java or C++, normalize negative remainders yourself.

Worked example: longest balanced subarray

Prompt: "Given an array of 0s and 1s, return the length of the longest contiguous subarray with equal numbers of each."

Start with the brute force (check every subarray, O(n²)), then the transformation: count a 1 as +1 and a 0 as -1. A balanced subarray is one that sums to 0, which means two equal running sums. For the longest, you want the earliest index where each running sum appeared, so store first occurrences, not counts.

def longest_balanced(bits):
    first_index = {0: -1}
    running = 0
    best = 0
    for i, b in enumerate(bits):
        running += 1 if b == 1 else -1
        if running in first_index:
            best = max(best, i - first_index[running])
        else:
            first_index[running] = i
    return best

Trace [0, 1, 1, 0, 1, 1]: running sums are -1, 0, 1, 0, 1, 2. At index 1 the sum 0 matches the seed at -1, length 2. At index 3 it matches again, length 4. At index 4 the sum 1 matches index 2, length 2. Answer: 4, the subarray 0, 1, 1, 0.

Then test aloud: all zeros (answer 0), an empty array (0), and a fully balanced array (its whole length, thanks to the 0: -1 seed). Never overwrite a first index: on [0, 1, 1, 0], overwriting returns 2 instead of 4.

What separates two answers here is mostly the rephrasing. A weaker candidate writes the O(n²) double loop, is asked for better, and tries a sliding window that cannot work because the condition is not monotonic. A stronger one names the brute force and its cost, then says the +1/-1 transformation and "two equal running sums bound a balanced subarray" before coding (problem solving), explains why the map stores first indexes rather than counts (code quality), traces the example (correctness), tests all zeros and a fully balanced array unprompted (testing and edge cases), and states O(n) time and O(n) space without being asked (communication).

Tip

For any "subarray with sum (or balance, or remainder) X" problem, say the rephrasing first: "a subarray ending here works when an earlier prefix equals current minus X." Then decide what the map stores: counts for "how many", first index for "longest".

Follow-ups to expect

The AI interviewer lets you drive, then asks for your complexity and your tests. On prefix-count problems, the first hint is usually a nudge toward the rephrasing ("what does a subarray sum look like in terms of running totals?"), and later hints name the map. Each hint is counted and weighs on the dimension it helped with, the near-solution one most. After a working solution, expect:

  • "What is the worst case of a hash map?" O(n) per operation with adversarial collisions; average O(1). Mention it, then move on.

  • "Can you do it in O(1) space?" Sometimes, by sorting first; not for the prefix-count problems in general.

  • "The array is huge and arrives as a stream." Prefix-count solutions work in one pass, but the map can grow with the number of distinct prefixes; say so.

  • "Support updates to the array between range queries." Plain prefix sums cost O(n) per update; a Fenwick tree or segment tree gives O(log n) for both. Naming it is usually enough.

What changes with seniority

Early-career candidates are expected to use a map for lookup and counting without prompting and to state the memory cost. Mid-level candidates should reach the prefix-count rephrasing with at most a nudge and choose counts or first indexes correctly. Senior candidates are expected to handle the variants (remainders, longest instead of count, streams) quickly and to discuss when a sorted approach or a Fenwick tree is the better trade.

Mistakes that cost points

  • Adding to the map before checking it, so an element pairs with itself.

  • Forgetting the empty-prefix seed ({0: 1} for counts, {0: -1} for indexes).

  • Using a mutable key such as a list.

  • Reaching for a sliding window when values can be negative.

  • Not stating the O(n) memory you are spending.

Practice it

Drill for 15 minutes: write count_subarrays_with_sum from memory and trace it on [3, 4, -7, 3, 1, 3, 1, -4] with k = 7 (the answer is 3: 3, 4, then 3, 1, 3, then the first six values). Then adapt it to return the length of the longest subarray with sum k, storing first indexes instead of counts.

Then take Two Sum live and narrate the lookup shape: ask the map about the past, then add the present. Previous in this series: Binary Search. Next: Stacks and Monotonic Stacks.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Stacks and Monotonic Stacks

    Solve nested-structure problems with a stack, find the next greater or smaller element for every position in one pass, and explain the push-once, pop-once reason it runs in linear time.

    8 min read

  • Heaps and Top K

    Recognize when a problem needs a heap, code its four shapes (top k, k-way merge, two heaps for a running median, scheduling by earliest end) and say when a plain sort or quickselect is the better answer.

    9 min read

  • Trees

    Decide whether information flows down a tree as arguments or up as return values, then write correct DFS, level-order BFS and BST solutions, including iterative traversal for trees too deep for recursion.

    9 min read

  • Graphs

    Model a problem as a graph and pick the right tool (BFS, DFS, topological sort, Dijkstra or union-find) while avoiding the visited-set and recursion-depth bugs that cost correctness points.

    9 min read