Subarray Sums: Hash Maps & Kadane’s Algorithm
Counting subarrays with sum k, and the maximum subarray in one pass.
In 1977 Ulf Grenander wanted the brightest rectangle in a digitized image and, to understand it, simplified it to one dimension: which run of consecutive numbers has the largest sum? He found an algorithm, Michael Shamos an one overnight, and Jay Kadane, hearing the problem at a Carnegie Mellon seminar, an one within a minute. Grenander's original two-dimensional problem is still stuck near , and since 2016 we know why: a truly faster algorithm for it would also give one for all-pairs shortest paths.
What you’ll learn
- Count the subarrays with sum in expected time with a hash map of prefix counts, prove it correct, and explain why holds without hashing in the algebraic computation tree model.
- Adapt the method to remainders, balanced 0/1 subarrays, XOR, and longest subarrays.
- Derive Kadane's algorithm both as dynamic programming and as "prefix minus the smallest earlier prefix", prove it optimal, and handle empty, all-negative, circular and length-limited variants.
- Solve the 2-D maximum subarray in , and state its fine-grained equivalence with all-pairs shortest paths.
Counting subarrays with sum k
How many subarrays of have sum exactly ? (Its prefix sums are .)
Show the answer
4
Pairs with : gives ; and give and , both found at because the value occurs twice among the earlier prefixes; and gives . That is 4, and it is why the map stores counts, not mere presence.
#include <chrono>
#include <cstdint>
#include <unordered_map>
#include <vector>
struct SplitMixHash { // randomized hash: resists anti-hash tests
static uint64_t mix(uint64_t x) { // the splitmix64 finalizer
x += 0x9e3779b97f4a7c15ULL;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
return x ^ (x >> 31);
}
size_t operator()(long long x) const {
static const uint64_t seed = std::chrono::steady_clock::now().time_since_epoch().count();
return mix((uint64_t)x + seed);
}
};
long long count_subarrays(const std::vector<long long>& a, long long k) {
std::unordered_map<long long, long long, SplitMixHash> seen;
seen[0] = 1; // the empty prefix P[0] = 0
long long prefix = 0, count = 0;
for (long long x : a) {
prefix += x;
auto it = seen.find(prefix - k);
if (it != seen.end()) count += it->second;
++seen[prefix];
}
return count; // 64-bit: up to n(n+1)/2 subarrays
}The contest idiom: std::unordered_map with a seeded mixing hash, so precomputed collision inputs fail. The count itself needs 64 bits: an all-zero array of length with has qualifying subarrays.
Remainders, balance, XOR and the longest subarray
The same pairing answers many questions; only the key and the lookup change.
- Sum divisible by : exactly when , so count pairs of equal remainders: if prefixes have remainder .
- Equal numbers of 0s and 1s: map and ; balanced subarrays are exactly the zero-sum ones.
- XOR equal to : with prefix XORs , look up , since .
- Longest subarray with sum : store the first index of each prefix value and maximize . For the shortest, keep the last index instead.
from collections import defaultdict
def count_divisible(a, k):
seen = defaultdict(int)
seen[0] = 1 # P[0] = 0 has remainder 0
prefix = count = 0
for x in a:
prefix = (prefix + x) % k # Python's % is never negative for k > 0
count += seen[prefix] # equal remainders: difference divisible by k
seen[prefix] += 1
return count
def longest_sum_k(a, k):
first = {0: 0} # prefix value -> FIRST index where it occurs
prefix = best = 0
for j, x in enumerate(a, start=1): # prefix = P[j]
prefix += x
if prefix - k in first:
best = max(best, j - first[prefix - k])
first.setdefault(prefix, j) # never overwrite: earlier means longer
return best
print(count_divisible([4, -2, 5, 1, -3, 6], 3)) # 7
bits = [1, 1, 0, 1, 0, 0, 1, 1, 1, 0]
print(longest_sum_k([1 if b else -1 for b in bits], 0)) # 8: bits[2..9]For the prefix remainders mod 3 are : one 0, two 1s and four 2s, so subarrays. In C++, normalize remainders with ((p % k) + k) % k.
In longest_sum_k, a prefix value that has occurred before is not overwritten (setdefault). What goes wrong if the code overwrote it with the latest index?
- Nothing: the answer is the same either way
- It would find the shortest qualifying subarray ending at each instead of the longest, and could miss the overall longest
- It would count some subarrays twice
- It would crash on negative numbers
Show the answer
B. It would find the shortest qualifying subarray ending at each instead of the longest, and could miss the overall longest
For a fixed right end , the subarray is longest when is the earliest index with . Keeping the latest index gives the shortest one. On the bit example the overwrite version never pairs with its first occurrence at index 2: it returns 6 instead of 8.
The maximum subarray: Kadane's algorithm
Two views give the same Kadane's algorithm for the maximum subarray:
- Prefix view. The best subarray ending just before is : subtract the smallest earlier prefix. Keep a running minimum of .
- Dynamic programming. Let be the best sum of a subarray ending at . Such a subarray is either alone or a subarray ending at extended by , so : extend or restart.
The recurrence is exhaustive: every non-empty subarray ending at is either the single element or ends at before is appended, so
Every subarray ends somewhere, so the answer is the best . Unrolling the recurrence links it to the prefix view:
Lower bound. Any correct algorithm reads all entries: if it never reads , set larger than the sum of the absolute values of all the others. Then the true answer includes and changes with it, while the algorithm's output cannot. So in every model, and the scan is optimal.
def max_subarray(a): # best sum of a NON-EMPTY subarray
best = cur = a[0]
for x in a[1:]:
cur = max(x, cur + x) # extend the run, or restart at x
best = max(best, cur)
return best
print(max_subarray([2, -5, 4, -1, 2, -6, 5, -2, 3, -4])) # 6, from a[6..8]If the empty subarray is allowed, start with best = cur = 0 and use cur = max(0, cur + x): the answer is then never negative. Read the problem statement; on an all-negative array the two conventions differ.
Run the non-empty version on . What is the largest value cur reaches before index 6, that is, over ?
Show the answer
5
cur takes the values on : it restarts at and extends through and to , the sum of . Then drops it to , it restarts at , and the overall best becomes , from .
Circular and length-limited variants
On a circular array, a subarray may wrap from the end back to the start. A wrapping subarray is the whole array minus a non-wrapping block in the middle, so the best wrapping sum is the total minus the minimum subarray sum, which is Kadane's algorithm on the negated array. One trap: if every element is negative, the minimum subarray is the whole array and the formula returns , the sum of an empty subarray.
def max_circular(a): # uses max_subarray from the previous step
best = max_subarray(a) # the best non-wrapping subarray
if best < 0: # all negative: wrapping would mean "empty"
return best
worst = -max_subarray([-x for x in a]) # the minimum subarray sum
return max(best, sum(a) - worst) # wrapping = total minus a middle block
print(max_circular([5, -3, -4, 6, -9, 4])) # 9 = 4 + 5, wrapping around the endWith a length limit on the subarray , the prefix view becomes : a minimum over a sliding window of the prefix array. A monotonic deque of candidate starts, with increasing prefix values, maintains it in amortized time per step, so the whole scan is (see Monotonic Queues in Dynamic Programming).
from collections import deque
def best_with_length(a, L, R): # max sum of a[i..j-1] with L <= j - i <= R
P = [0]
for x in a:
P.append(P[-1] + x)
dq, best = deque(), float('-inf') # candidate starts i, P[i] increasing
for j in range(L, len(a) + 1):
i = j - L # the newest start allowed for this end
while dq and P[dq[-1]] >= P[i]:
dq.pop() # a later start with a smaller prefix dominates
dq.append(i)
while dq[0] < j - R:
dq.popleft() # too far left: the subarray would be too long
best = max(best, P[j] - P[dq[0]])
return bestWith and nothing ever leaves the window, the deque's front is just the running minimum of the prefix array, and this is Kadane's prefix view again.
Two dimensions and the APSP barrier
Grenander's real question was a rectangle. For an matrix, fix the top and bottom rows, squash the band between them into one array of column sums, and run Kadane on it: , which is for . Compare for trying every rectangle with a summed-area table, and for summing every rectangle from scratch.
def max_rectangle(g): # O(R^2 C): fix the top and bottom rows
R, C = len(g), len(g[0])
best = float('-inf')
for top in range(R):
col = [0] * C # col[c] = sum of g[top..bot][c]
for bot in range(top, R):
for c in range(C):
col[c] += g[bot][c]
best = max(best, max_subarray(col)) # Kadane on the squashed band
return best
print(max_rectangle([[1, -2, 3], [-4, 5, -1], [2, 2, -3]])) # 7The APSP conjecture of fine-grained complexity states that no algorithm solves all-pairs shortest paths on -vertex graphs with integer weights polynomial in . If it holds, the squash-and-Kadane algorithm is optimal up to factors. Smaller savings do exist: through the reduction to distance products, Williams's (2014) algorithm for APSP solves the 2-D maximum subarray just as fast.
Notice the scale: the input has numbers, so the conjectured optimum is , while the 1-D problem is linear. For arbitrary weighted points in the plane, the best box takes , and Backurs, Dikkala and Tzamos showed that would beat the best known max-weight clique algorithms.
Key takeaways
- Subarrays with sum are pairs with ; a hash map of prefix counts finds them all in one pass, expected, while without hashing deciding even needs in the algebraic computation tree model.
- Changing the key handles divisibility (remainders), balance () and XOR; storing first or last indices gives longest or shortest subarrays.
- Kadane's algorithm is "extend or restart", , equivalently the prefix sum minus the smallest earlier prefix; it is optimal because every element must be read.
- Circular arrays add "total minus the minimum subarray" (except when all values are negative); length limits turn the running minimum into a monotonic-deque window minimum, still .
- The 2-D maximum subarray takes by squashing row bands, and a truly subcubic algorithm would also give one for all-pairs shortest paths, and vice versa.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
When counting subarrays with sum , why does the hash map store how many times each prefix value occurred, rather than just whether it occurred?
- Because one right end can close several qualifying subarrays at once, one for each earlier with
- To handle negative numbers, which make prefix sums decrease
- To find the longest subarray
- Because hash maps cannot store booleans efficiently
Show the answer
A. Because one right end can close several qualifying subarrays at once, one for each earlier with
Repeated prefix values mean repeated starts. In with , the value occurs at and , so closes two subarrays.
A problem asks for the maximum sum of a non-empty subarray of . A solution initializes best = cur = 0 and updates cur = max(0, cur + x). What does it return, and what is correct?
- It returns , which is correct
- It returns , but the correct answer is
- It returns , but the correct answer is
- It returns , which is correct
Show the answer
B. It returns , but the correct answer is
That code implements the convention where the empty subarray (sum ) is allowed. With non-empty subarrays only, the best is the largest element, ; initialize with and use .
Suppose someone finds an algorithm for the maximum-sum rectangle in an matrix of integers. What would follow?
- Nothing in particular; the algorithm was never claimed to be optimal
- P would equal NP
- A truly subcubic algorithm for all-pairs shortest paths, refuting the APSP conjecture
- A linear-time algorithm for the 1-D maximum subarray
Show the answer
C. A truly subcubic algorithm for all-pairs shortest paths, refuting the APSP conjecture
Backurs, Dikkala and Tzamos (2016) showed that an algorithm for the maximum subarray gives an algorithm for APSP. Together with the reduction in the other direction (Tamaki & Tokuyama, 1998), the two problems are subcubic-equivalent.
The circular maximum subarray is computed as . On , why must the code return Kadane's answer directly?
- Because the total is negative, so subtraction overflows
- Because the minimum subarray is the whole array, so total minus it is , the sum of an empty subarray
- Because Kadane's algorithm fails on circular arrays
- It need not: the formula already returns
Show the answer
B. Because the minimum subarray is the whole array, so total minus it is , the sum of an empty subarray
A wrapping subarray must leave out a middle block; leaving out everything leaves nothing. With all elements negative the formula gives , which corresponds to no subarray at all. The correct answer is the best non-empty subarray, .
Further reading
- J. Bentley, "Programming pearls: algorithm design techniques," Communications of the ACM 27(9) (1984), 865–873.
- M. Ben-Or, "Lower bounds for algebraic computation trees," Proceedings of STOC (1983), 80–86.
- H. Tamaki & T. Tokuyama, "Algorithms for the maximum subarray problem based on matrix multiplication," Proceedings of SODA (1998), 446–452.
- A. Backurs, N. Dikkala & C. Tzamos, "Tight hardness results for maximum weight rectangles," Proceedings of ICALP (2016), 81:1–81:13.
- V. Vassilevska Williams & R. Williams, "Subcubic equivalences between path, matrix, and triangle problems," Journal of the ACM (2018); conference version in Proceedings of FOCS (2010).