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.
- 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:
- Two Sum: Find two indices
(i, j)wherenums[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
dictso findingtarget - numtakesO(1)→O(n)time,O(n)space.
- Brute force checks every pair
- Subarray Sum Equals
k: Count contiguous subarrays summing tok(even with negative numbers!).- Brute force recomputes every slice
nums[L : R + 1]→O(n²)orO(n³). - Prefix Sum + Hash Map tracks how many times each running total has appeared so far →
O(n)time,O(n)space.
- Brute force recomputes every slice
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) | num | needed = 9 - num | needed in seen? | Action | seen After Step |
|---|---|---|---|---|---|
0 | 2 | 7 | No | Store seen[2] = 0 | 2 -> 0 |
1 | 11 | -2 | No | Store seen[11] = 1 | 2 -> 0, 11 -> 1 |
2 | 7 | 2 | Yes (0)! | Return (0, 2) immediately | — |
Line-by-Line Walkthrough & Edge Cases
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:BEFOREseen[num] = i? Iftarget = 6andnums = [3, 3], checking before inserting ensures index0is never paired with itself—yet when index1arrives,seen[3] = 0is 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 lengthk):key = tuple(sorted(word)) - 26-letter frequency key (
O(k)per word): Build a 26-slot count list for lowercase'a'..'z', then convert totuple(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 torunning - (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).
| Index | x | running | running - k | Matches in prefix_counts | total | prefix_counts Updated |
|---|---|---|---|---|---|---|
| Start | — | 0 | — | — | 0 | 0: 1 |
0 | 1 | 1 | -2 | 0 | 0 | 0: 1, 1: 1 |
1 | 2 | 3 | 0 | 1 (subarray [1, 2]) | 1 | 0: 1, 1: 1, 3: 1 |
2 | 3 | 6 | 3 | 1 (subarray [3]) | 2 | 0: 1, 1: 1, 3: 1, 6: 1 |
3 | -2 | 4 | 1 | 1 (subarray [2, 3, -2]) | 3 | 0: 1, 1: 1, 3: 1, 4: 1, 6: 1 |
4 | 2 | 6 | 3 | 1 (subarray [3, -2, 2]) | 4 | 0: 1, 1: 1, 3: 1, 4: 1, 6: 2 |
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).
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 Signal | Best Pattern | Why |
|---|---|---|
| Find pair/indices with target sum or duplicate check | Hash Map / Set | O(1) complement or membership lookup |
| Group items by normalized signature (anagrams, shifted strings) | defaultdict(list) + tuple key | Immutable hashable signature groups equivalents |
Subarray sum equals k with negative numbers | Prefix Sum + Hash Map | Sliding window breaks when negatives exist! |
| Longest/shortest subarray with all positive numbers | Sliding Window | Shrinking 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:
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
What are the time and space complexities of the optimal hash-map two_sum algorithm?
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?
Why should you use Prefix Sum + Hash Map instead of Sliding Window for Subarray Sum Equals K when nums can contain negative numbers?