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 average-time membership check.
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 satisfying . Checking all pairs requires comparisons, which scales as .
Instead, iterate left to right. At index , the only partner that matters is need = target - x, and every valid partner index 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:
- An element never matches against itself when
target = 2 * x. - Duplicate values overwrite only after checking against earlier occurrences, so
[3, 3]withtarget = 6returns[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 ?". 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 and turns any contiguous subarray sum over into a subtraction:
Setting that difference equal to gives . Once again, the question reduces to Two Sum over cumulative totals: as you compute running at step , count how many earlier prefixes equal running - k.
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 , ensuring any subarray beginning at index 0 with sum 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.
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:
two_sum([2,7,11,15], 9): (0, 1)
subarrays([1,-1,0], 0): 3Why 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 average time assuming low collision rates, and degrade to in pathological worst-case hash collisions.
| Pattern Variant | Time (Average) | Time (Worst) | Extra Space |
|---|---|---|---|
Two Sum (dict) | |||
Subarray Sum Counts (dict + prefix) | |||
Sorted Two Pointers (sort + scan) | auxiliary |
In practice, CPython randomizes string hashes per process and mixes integer hashes cleanly, so 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] = idxorcounts[running] += 1first causes an element to match itself whentarget = 2 * valork = 0matches an empty zero-length slice. - Forgetting the empty prefix: Initializing
counts = defaultdict(int)withoutcounts[0] = 1misses every valid prefix subarray starting at index0. - 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
listkeys totupleor immutablestrsignatures first.
I skip hash maps in two concrete situations. First, when the array is already sorted and memory must remain , 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:
- Two Sum: Practice single-pass complement indexing, duplicate value handling, and clarifying return order guarantees.
- Subarray Sum Equals K: Practice
running - kprefix counting on arrays containing zeros and negative integers.
