Data Structures and Algorithms5 min read

Hash Maps, Prefix Sums, and the Two-Sum Family in Coding Interviews

How complement lookup and prefix-sum hash maps turn quadratic array scans into single-pass linear solutions, when sorting beats hashing, and how negative numbers break sliding windows.

The Two-Sum family trades linear auxiliary memory in a hash map for constant-time average complement lookups, dropping nested quadratic loops to a single linear pass. When the target shifts from two discrete indices to a contiguous range sum with negative numbers, combining a running prefix sum with a hash map of prior prefix counts preserves linear runtime where a sliding window fails.

Key takeaways

  • Every nested pair loop checking an algebraic relation f(a, b) = target can ask whether f(a) or b is already indexed.
  • Prefix-sum subtraction converts contiguous subarray queries into two-point differences on cumulative state.
  • Sorted two-pointer scans beat hash maps when memory is tightly bounded or duplicate triplets must be skipped.

Quick facts

  • Query the complement map before inserting the current element so an index never pairs with itself.
  • Python dict lookup, insertion, and membership tests run in O(1) average time and O(n) worst-case collision time.
  • Seeding prefix counts with {0: 1} catches every valid subarray that starts at index zero.
  • Sliding windows fail on subarray sum queries whenever the array contains negative integers.

Why Arrays and Hashing Sit at the Root of Every Roadmap

When I coach engineers preparing for coding loops, I always start with hash maps even when they think they already know them. On the NeetCode roadmap walkthrough, Arrays and Hashing sits at the very top of the dependency tree for good reason: weak indexing habits leak into trees, graphs, and dynamic programming later.

The core shift in thinking is simple. Whenever a naive solution scans backward with a second loop to ask "have I already seen a value that completes my target?", a hash map turns that backward scan into an O(1)O(1) average-time membership check.

Hash map complement lookup and prefix sum architecture
Hash map complement lookup and prefix sum architecture

Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).

Intuition and the Complement Invariant

1. Discrete pairs: query before you insert

Suppose you need two distinct indices i<ji < j satisfying ai+aj=Ta_i + a_j = T. Checking all pairs requires (n2)\binom{n}{2} comparisons, which scales as O(n2)O(n^2).

Instead, iterate left to right. At index jj, the only partner that matters is need = target - x, and every valid partner index i<ji < j is already sitting in a dictionary seen mapping value to index.

If you check need in seen before running seen[x] = j, two guarantees hold at once:

  1. An element never matches against itself when target = 2 * x.
  2. Duplicate values overwrite only after checking against earlier occurrences, so [3, 3] with target = 6 returns [0, 1] cleanly.

If you need all index pairs rather than one pair, store a list of indices or a frequency count per value instead of a single integer index. Beyond integer sums, the exact same map-by-signature pattern powers grouping problems like Group Anagrams: compute an invariant key per item, such as a sorted string or a 26-letter frequency tuple, and append each original string into groups[key]. Comparing signatures via dictionary buckets drops all-pairs string comparison from quadratic to linear in total character count.

2. Contiguous ranges: turning subarrays into prefix differences

Now suppose the interviewer pivots from "two indices" to "how many contiguous subarrays sum to kk?". If the array holds strictly positive numbers, I reach for a sliding window. The moment negative values or zeros appear, expanding right can decrease the sum and shrinking left can increase it, so window monotonicity breaks.

As the USACO Guide prefix sums chapter formalizes, defining P0=0P_0 = 0 and Pt=∑m=0t−1amP_t = \sum_{m=0}^{t-1} a_m turns any contiguous subarray sum over [i,j][i, j] into a subtraction:

∑m=ijam=Pj+1−Pi\sum_{m=i}^{j} a_m = P_{j+1} - P_i$$\sum_{m=i}^{j} a_m = P_{j+1} - P_i$$

Setting that difference equal to kk gives Pi=Pj+1−kP_i = P_{j+1} - k. Once again, the question reduces to Two Sum over cumulative totals: as you compute running at step jj, count how many earlier prefixes equal running - k.

Step-by-step prefix sum hash map trace for target k equals 5
Step-by-step prefix sum hash map trace for target k equals 5

Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).

Notice why counts = {0: 1} is mandatory before the loop begins. That single entry represents the empty prefix P0=0P_0 = 0, ensuring any subarray beginning at index 0 with sum kk finds a match without special-case branching.

Working Python Implementations

Here are both canonical templates written as clean, self-contained functions with verification cases. Notice how two_sum returns indices immediately upon finding a complement, while count_subarrays_with_sum accumulates frequencies before updating counts.

PYTHON
from collections import defaultdict


def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    seen: dict[int, int] = {}
    for idx, val in enumerate(nums):
        need = target - val
        if need in seen:
            return (seen[need], idx)
        seen[val] = idx
    return None


def count_subarrays_with_sum(nums: list[int], k: int) -> int:
    counts: dict[int, int] = defaultdict(int)
    counts[0] = 1
    running = 0
    total = 0

    for val in nums:
        running += val
        total += counts[running - k]
        counts[running] += 1

    return total


if __name__ == "__main__":
    assert two_sum([2, 7, 11, 15], 9) == (0, 1)
    assert two_sum([3, 3], 6) == (0, 1)
    assert two_sum([3, 2, 4], 6) == (1, 2)
    assert count_subarrays_with_sum([3, 4, -1, 2, 1], 5) == 1
    assert count_subarrays_with_sum([1, -1, 0], 0) == 3
    print("two_sum([2,7,11,15], 9):", two_sum([2, 7, 11, 15], 9))
    print("subarrays([1,-1,0], 0):", count_subarrays_with_sum([1, -1, 0], 0))

Running this script produces:

TEXT
two_sum([2,7,11,15], 9): (0, 1)
subarrays([1,-1,0], 0): 3

Why did [1, -1, 0] with k = 0 return 3? The qualifying slices are [1, -1], [1, -1, 0], and [0], each corresponding to repeated prefix values in counts.

Time and Space Complexity

According to the Python built-in time complexity documentation, dict lookup (key in d), d[key], and amortized insertion d[key] = value run in O(1)O(1) average time assuming low collision rates, and degrade to O(n)O(n) in pathological worst-case hash collisions.

Pattern VariantTime (Average)Time (Worst)Extra Space
Two Sum (dict)O(n)O(n)O(n2)O(n^2)O(n)O(n)
Subarray Sum Counts (dict + prefix)O(n)O(n)O(n2)O(n^2)O(n)O(n)
Sorted Two Pointers (sort + scan)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(1)O(1) auxiliary

In practice, CPython randomizes string hashes per process and mixes integer hashes cleanly, so O(n)O(n) holds reliably across interview tests. Remember that counts.copy() or iterating over keys after removals still scales with the internal hash table capacity until a resize occurs.

Common Mistakes and When I Skip Hashing

I regularly see four bugs when candidates implement this family under time pressure:

  • Updating the map before querying: Inserting seen[val] = idx or counts[running] += 1 first causes an element to match itself when target = 2 * val or k = 0 matches an empty zero-length slice.
  • Forgetting the empty prefix: Initializing counts = defaultdict(int) without counts[0] = 1 misses every valid prefix subarray starting at index 0.
  • Reaching for a sliding window on negative inputs: A shrinking pointer loses validity once numbers can drop below zero, because shortening a window may raise its sum.
  • Using unhashable keys directly: Grouping anagrams or coordinate sets requires converting list keys to tuple or immutable str signatures first.

I skip hash maps in two concrete situations. First, when the array is already sorted and memory must remain O(1)O(1), two converging pointers solve pair sum cleanly without allocating a dictionary. Second, when the problem expands to three or more elements with strict duplicate suppression (like 3-Sum), sorting plus two pointers avoids messy triplet-deduplication sets.

Practice Problems

Apply both templates without reading solutions first:

  1. Two Sum: Practice single-pass complement indexing, duplicate value handling, and clarifying return order guarantees.
  2. Subarray Sum Equals K: Practice running - k prefix counting on arrays containing zeros and negative integers.

Sources