1. Complexity Analysis & Python Under the Hood

Arrays, Hash Maps (dict/set) & Prefix Sums

Solve classic array problems in O(n) time instead of O(n²) brute force: master complement hash maps (Two Sum), anagram grouping keys, and prefix sum range queries.

7 min readUpdated 2026-11-30
In This Lesson
  • Trade O(n) space in a dict/set to eliminate nested O(n²) loops
  • Use immutable tuples as dictionary keys for grouping (e.g., character counts)
  • Answer arbitrary subarray sum queries in O(1) using prefix sums

Nearly half of all coding interview array problems collapse from O(n²) to O(n) the moment you ask: "What information can I remember in a dict, set, or prefix array as I walk through the array once?"

Why It Matters: The Problem with Brute Force

Consider two fundamental questions on an unsorted integer array nums of length n:

  1. Two Sum: Find two indices (i, j) where nums[i] + nums[j] == target.
    • Brute force checks every pair (i, j) with nested loops → O(n²) time, O(1) space.
    • Complement Hash Map stores each visited value's index in a dict so finding target - num takes O(1) → O(n) time, O(n) space.
  2. Subarray Sum Equals k: Count contiguous subarrays summing to k (even with negative numbers!).
    • Brute force recomputes every slice nums[L : R + 1] → O(n²) or O(n³).
    • Prefix Sum + Hash Map tracks how many times each running total has appeared so far → O(n) time, O(n) space.

Pattern 1: Complement Lookup (two_sum)

Mental Model & Step-by-Step Dry-Run Trace

Instead of searching forward for a partner for nums[i], walk left-to-right and ask: "Have I already seen the exact complement needed = target - nums[i]?"

Trace nums = [2, 11, 7, 15], target = 9:

Step (i)numneeded = 9 - numneeded in seen?Actionseen After Step
027NoStore seen[2] = 02 -> 0
111-2NoStore seen[11] = 12 -> 0, 11 -> 1
272Yes (0)!Return (0, 2) immediately—

Line-by-Line Walkthrough & Edge Cases

python
from typing import Optional

def two_sum(nums: list[int], target: int) -> Optional[tuple[int, int]]:
    seen: dict[int, int] = {}
    for i, num in enumerate(nums):
        needed = target - num
        if needed in seen:
            return (seen[needed], i)
        seen[num] = i
    return None
  • Why check if needed in seen: BEFORE seen[num] = i? If target = 6 and nums = [3, 3], checking before inserting ensures index 0 is never paired with itself—yet when index 1 arrives, seen[3] = 0 is found, returning (0, 1) cleanly!
  • Empty or 1-element list: The loop completes (or skips) and returns None.
  • Negative numbers & zero: Hash maps handle negatives (-4 + 13 = 9) identically to positives.

Pattern 2: Immutable Grouping Keys (group_anagrams)

Two words are anagrams if and only if they have the exact same character frequencies (or sorted letters). In Python, a list cannot be a dict key because lists are mutable and unhashable. Convert the signature into an immutable tuple!

  • Sorted key (O(k log k) per word of length k): key = tuple(sorted(word))
  • 26-letter frequency key (O(k) per word): Build a 26-slot count list for lowercase 'a'..'z', then convert to tuple(counts).

Pattern 3: Prefix Sums & Subarray Sum Equals k

Mental Model & Dry-Run Trace

A prefix sum array P of length n + 1 (with P[0] = 0) stores P[i] = sum(nums[:i]). Any range sum nums[L : R + 1] equals P[R + 1] - P[L] in O(1).

Now apply that exact equation to count subarrays summing to k:

  • Suppose the running total up to the current index is running.
  • If a previous prefix had sum running - k, then the slice between that earlier index and here sums to running - (running - k) = k!

Trace nums = [1, 2, 3, -2, 2], k = 3: Initialize prefix_counts with 0 -> 1 (representing the empty prefix before index 0).

Indexxrunningrunning - kMatches in prefix_countstotalprefix_counts Updated
Start—0——00: 1
011-2000: 1, 1: 1
12301 (subarray [1, 2])10: 1, 1: 1, 3: 1
23631 (subarray [3])20: 1, 1: 1, 3: 1, 6: 1
3-2411 (subarray [2, 3, -2])30: 1, 1: 1, 3: 1, 4: 1, 6: 1
42631 (subarray [3, -2, 2])40: 1, 1: 1, 3: 1, 4: 1, 6: 2
Forgetting {0: 1} in Prefix Sum Counting

If you initialize prefix_counts empty instead of starting with 0 -> 1, you will miss every valid subarray that starts right at index 0 (like [1, 2] above when running == k and running - k == 0).

Always Use defaultdict or .get() for Frequency Maps

counts[key] = counts.get(key, 0) + 1 or from collections import defaultdict prevents KeyError crashes and keeps counting loops clean and bug-free.

Pattern Recognition: Hash Map + Prefix Sum vs Sliding Window

Problem SignalBest PatternWhy
Find pair/indices with target sum or duplicate checkHash Map / SetO(1) complement or membership lookup
Group items by normalized signature (anagrams, shifted strings)defaultdict(list) + tuple keyImmutable hashable signature groups equivalents
Subarray sum equals k with negative numbersPrefix Sum + Hash MapSliding window breaks when negatives exist!
Longest/shortest subarray with all positive numbersSliding WindowShrinking reliably decreases the sum (O(1) space)

Try It Yourself in the Playground

Test two_sum, group_anagrams, and count_subarrays_with_sum (including negative numbers and edge cases) live below:

Python 3Try It Live: Hash Maps & Prefix Sum Subarrays
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why did group_anagrams convert sorted(w) into tuple(sorted(w)) before using it as a dictionary key?

Quick Checkpoints

Check Your Understanding

What are the time and space complexities of the optimal hash-map two_sum algorithm?

Check Your Understanding

Once a prefix sum array P of length n + 1 is built (with P[0] = 0), how do you compute the sum of nums[left : right + 1] in O(1) time?

Check Your Understanding

Why should you use Prefix Sum + Hash Map instead of Sliding Window for Subarray Sum Equals K when nums can contain negative numbers?