Step 04 Hashing — Theory
Basic Hashing
Hashing is the technique of turning a value into a direct memory address so it can be found in (average) constant time. In this module you use it in its most powerful competitive-programming form: not just counting frequencies, but combining a hash map with prefix sums to answer questions about subarrays — longest subarray with a given sum, how many subarrays have a given sum or XOR — in one linear pass.
What a hash map actually does
A hash map stores key-value pairs. When you insert a key, a hash function converts it into a bucket index, and the pair is stored in that bucket. Looking the key up later means hashing it again and jumping straight to the same bucket, so insert, lookup and delete are O(1) on average.
Collisions — two different keys landing in the same bucket — are handled by chaining (each bucket holds a small list of pairs) or open addressing. As the table fills up, a load factor threshold triggers a resize and rehash so buckets stay short. You rarely implement this yourself: Python's dict and set, C++'s unordered_map and Java's HashMap are all hash maps. What you must internalise is the cost model: average O(1) per operation, worst case O(n) if many keys collide, and O(n) extra space.
freq = {}
for x in arr:
freq[x] = freq.get(x, 0) + 1 # insert / update: average O(1)
if target in freq: # lookup: average O(1)
print(freq[target])The frequency-map pattern
The simplest hashing pattern is counting how often each value occurs. One pass builds the frequency map; after that, questions like 'does any element appear twice?', 'is this a valid anagram?' or 'what is the majority element?' become quick lookups instead of nested loops.
A close cousin is the 'have I seen this before?' set. While scanning left to right, a set of seen values lets you detect duplicates, find the first repeated element, or check membership in O(1) per step. Whenever a brute-force solution has an inner loop that only searches for a value, a hash set or map usually deletes that loop.
Prefix sums + hashing: the subarray trick
Let prefix[i] be the sum of the first i elements. The sum of the subarray (j+1 .. i) is prefix[i] - prefix[j]. So a subarray ending at i has sum K exactly when some earlier prefix equals prefix[i] - K.
While scanning, keep a hash map of prefixes you have already seen. At each step compute the running prefix P, then ask the map: have I seen P - K? If yes, a subarray ending here sums to K. For the LONGEST such subarray, store only the first (earliest) index of each prefix. For COUNTING subarrays, store how many times each prefix occurred and add that count to the answer.
The one detail everyone forgets: seed the map with prefix 0 before the scan starts (index -1 for the longest version, count 1 for the counting version). That represents the empty prefix before the array begins, and without it, subarrays starting at index 0 are missed.
def longest_subarray_with_sum(arr, k):
first_seen = {0: -1} # prefix sum -> earliest index
prefix = 0
best = 0
for i, x in enumerate(arr):
prefix += x
if prefix - k in first_seen:
best = max(best, i - first_seen[prefix - k])
if prefix not in first_seen: # keep earliest only
first_seen[prefix] = i
return bestWorked example: longest subarray with sum 3
Take arr = [1, -1, 5, -2, 3] and K = 3. Running prefixes (with the seeded 0 at index -1) are: 0, 1, 0, 5, 3, 6.
At the last element the prefix is 6, and 6 - 3 = 3 was first seen at index 3, giving length 5 - 3 = 2... but the better hit comes earlier: when the prefix is 3 (after the fourth element, index 3), 3 - 3 = 0 matches the seeded prefix at index -1, giving length 3 - (-1) = 4. That is the subarray [1, -1, 5, -2], which indeed sums to 3, and it is the longest.
Notice why this module needs hashing at all: the array contains negatives, so prefix sums go up and down. Sliding window relies on sums moving in one direction only, so it cannot be used here — the hash map version works for any integers.
Complexity and common mistakes
The prefix + hash approach is O(n) average time and O(n) space, against O(n^2) for checking all subarrays. The same skeleton solves the XOR variant (prefix XOR instead of prefix sum, using the fact that x XOR x = 0) and 'largest subarray with sum 0' (K = 0).
Common mistakes: (1) overwriting the stored index of a prefix — for longest problems you must keep the earliest occurrence, for counting you must accumulate counts, and mixing the two recipes gives wrong answers; (2) forgetting the seeded prefix 0; (3) reaching for a hash map when order matters — hash maps do not remember insertion order of keys for range questions, and they cannot answer 'smallest value greater than x' (that needs a balanced BST / sorted structure); (4) in languages like C++, using unordered_map with hackable hash functions can be forced into worst-case collisions, so competitive programmers often use gp_hash_table or sort + coordinate compression instead.
Key points
- Hash maps give average O(1) insert, lookup and delete; worst case degrades to O(n) under heavy collisions.
- Subarray sum K exists ending at i iff an earlier prefix equals prefix[i] - K — store prefixes in a hash map.
- Always seed the map with prefix 0 (earliest index -1, or count 1) so subarrays starting at index 0 are counted.
- For LONGEST subarray keep the first occurrence of each prefix; for COUNTING keep occurrence counts — never mix the two.
- Negative numbers kill sliding window but not prefix + hashing; the XOR version uses prefix XOR instead of prefix sum.