Arrays & Hashing
When to use: you need O(1) lookups ("have I seen X?", "how many times?", "where was X?"), grouping by a key, or counting.
- Hash set: membership / duplicates.
- Hash map: value → index / count / group.
- Prefix sums + map: "number of subarrays with sum = k" in O(n):
sum(i..j) = pre[j+1] - pre[i]. - In-place index tricks: when values are in
[1..n], use the array itself as the hash table.
# prefix-sum + hashmap template: count subarrays whose sum == k
count, pre, seen = 0, 0, {0: 1}
for x in nums:
pre += x
count += seen.get(pre - k, 0)
seen[pre] = seen.get(pre, 0) + 1
Problems
Showing 42 of 42