Skip to content

Hash maps and prefix information

A hash map associates a key with a value. Python provides this structure as dict. Use it when you need an earlier value’s position, a frequency, or information about a prefix already processed.

The examples use invented integer sequences. Read arrays and Python lists first if indexed access is unfamiliar.

Keys must be hashable, so an integer or a string works, while a mutable list does not. Assigning an existing key replaces its value. counts.get(value, 0) returns zero when the key is absent, without inserting it.

counts: dict[int, int] = {}
for value in [4, 1, 4, 2, 1]:
counts[value] = counts.get(value, 0) + 1
print("Read:", value, "Counts:", counts)
print("Count for missing key 9:", counts.get(9, 0))
print("Key 9 exists:", 9 in counts)
Read: 4 Counts: {4: 1}
Read: 1 Counts: {4: 1, 1: 1}
Read: 4 Counts: {4: 2, 1: 1}
Read: 2 Counts: {4: 2, 1: 1, 2: 1}
Read: 1 Counts: {4: 2, 1: 2, 2: 1}
Count for missing key 9: 0
Key 9 exists: False

Dictionaries preserve insertion order, but that order is not numerical order. Here, repeated values update their existing entries. A set can answer whether a value appeared, but cannot preserve its frequency alone.

Count contiguous segments with a target sum

Section titled “Count contiguous segments with a target sum”

A record contains signed changes in a balance. Count its nonempty contiguous segments whose sum equals a target. The example uses [2, -1, 2, 1] and a target of 3. Negative values are allowed, so a window cannot decide whether to shrink from its sum alone.

Let prefix be the sum up to the current position. A segment ending here has the target sum when an earlier prefix equals prefix - target. Store the number of times each earlier prefix occurred. The initial {0: 1} represents the empty prefix before the first element.

def count_target_segments(values: list[int], target: int) -> int:
"""Count nonempty contiguous segments with the requested sum.
Args:
values: Signed integer values in their original order.
target: Required sum of each counted segment.
Returns:
The number of contiguous segments whose sum equals target.
"""
prefix_counts = {0: 1}
prefix = 0
total = 0
for value in values:
prefix += value
total += prefix_counts.get(prefix - target, 0)
prefix_counts[prefix] = prefix_counts.get(prefix, 0) + 1
return total
changes = [2, -1, 2, 1]
target = 3
prefix_counts = {0: 1}
prefix = 0
total = 0
print("index prefix needed matches total counts")
for index, value in enumerate(changes):
prefix += value
needed = prefix - target
matches = prefix_counts.get(needed, 0)
total += matches
prefix_counts[prefix] = prefix_counts.get(prefix, 0) + 1
print(index, prefix, needed, matches, total, prefix_counts)
print("Segment count:", count_target_segments(changes, target))
index prefix needed matches total counts
0 2 -1 0 0 {0: 1, 2: 1}
1 1 -2 0 0 {0: 1, 2: 1, 1: 1}
2 3 0 1 1 {0: 1, 2: 1, 1: 1, 3: 1}
3 4 1 1 2 {0: 1, 2: 1, 1: 1, 3: 1, 4: 1}
Segment count: 2

Before each update, the dictionary counts only earlier prefixes. This invariant makes each lookup count exactly the segments ending at the current position. Add the current prefix after the lookup; otherwise, a zero target would count an empty segment. Keep frequencies rather than a set because different earlier positions can have the same prefix sum.

For n values, the function performs a constant number of dictionary operations per value. Its expected time is O(n), and its auxiliary space is O(n) for distinct prefix sums. Dictionary lookup and insertion have expected O(1) cost under ordinary hash distributions. Collisions can make an individual operation O(n), so the algorithm’s collision worst case is O(n²).

These bounds treat integer addition, hashing, and comparison as constant-time operations. Python integers have arbitrary precision; operations on increasingly long integers also depend on their bit length. The trace prints the full dictionary repeatedly, so its display cost is separate from the function’s cost.

assert count_target_segments([], 0) == 0
assert count_target_segments([0], 0) == 1
assert count_target_segments([0, 0], 0) == 3
assert count_target_segments([2, -2, 2], 2) == 3
assert count_target_segments([5, 6], 1) == 0
print("Boundary checks passed.")
Boundary checks passed.
  • Solve Two Sum with a dictionary of earlier positions. Explain why you check for the complement before storing the current position.
  • Solve Subarray Sum Equals K with prefix frequencies. Include repeated prefixes and a zero target in your tests.

Download the Python source to run the complete example locally.

Python’s dictionary documentation defines key lookup, get, and insertion order. These details determine the frequency example’s behavior.

The Python design FAQ explains CPython’s hash table representation. It provides the implementation context for expected constant-time lookup.

MIT’s hashing lecture explains how hash tables support efficient search. It develops the assumptions behind expected operation costs.