Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 O(n2)O(n^2) algorithm, Michael Shamos an O(nlog⁡n)O(n\log n) one overnight, and Jay Kadane, hearing the problem at a Carnegie Mellon seminar, an O(n)O(n) one within a minute. Grenander's original two-dimensional problem is still stuck near n3n^3, 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 kk in O(n)O(n) expected time with a hash map of prefix counts, prove it correct, and explain why Ω(nlog⁡n)\Omega(n\log n) 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 O(n3)O(n^3), and state its fine-grained equivalence with all-pairs shortest paths.

Counting subarrays with sum k

Predict before you look

How many subarrays of a=[3,4,−7,1,3,3,1,−4]a=[3,4,-7,1,3,3,1,-4] have sum exactly 77? (Its prefix sums are P=[0,3,7,0,1,4,7,8,4]P=[0,3,7,0,1,4,7,8,4].)

Show the answer

4

Pairs with P[j]−P[i]=7P[j]-P[i]=7: (0,2)(0,2) gives a[0..1]a[0..1]; (0,6)(0,6) and (3,6)(3,6) give a[0..5]a[0..5] and a[3..5]a[3..5], both found at j=6j=6 because the value 00 occurs twice among the earlier prefixes; and (4,7)(4,7) gives a[4..6]a[4..6]. That is 4, and it is why the map stores counts, not mere presence.

cpp
#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 10510^5 with k=0k=0 has 5,000,050,0005{,}000{,}050{,}000 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 kk: P[j]−P[i]≡0(modk)P[j]-P[i]\equiv0\pmod k exactly when P[i]≡P[j](modk)P[i]\equiv P[j]\pmod k, so count pairs of equal remainders: ∑r(cr2)\sum_r\binom{c_r}{2} if crc_r prefixes have remainder rr.
  • Equal numbers of 0s and 1s: map 0↦−10\mapsto-1 and 1↦+11\mapsto+1; balanced subarrays are exactly the zero-sum ones.
  • XOR equal to kk: with prefix XORs XX, look up X[j]⊕kX[j]\oplus k, since X[i]⊕X[j]=k  ⟺  X[i]=X[j]⊕kX[i]\oplus X[j]=k\iff X[i]=X[j]\oplus k.
  • Longest subarray with sum kk: store the first index of each prefix value and maximize j−first[P[j]−k]j-\text{first}[P[j]-k]. For the shortest, keep the last index instead.
python
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 [4,−2,5,1,−3,6][4,-2,5,1,-3,6] the prefix remainders mod 3 are [0,1,2,1,2,2,2][0,1,2,1,2,2,2]: one 0, two 1s and four 2s, so 0+1+6=70+1+6=7 subarrays. In C++, normalize remainders with ((p % k) + k) % k.

Check your understanding

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?

  1. Nothing: the answer is the same either way
  2. It would find the shortest qualifying subarray ending at each jj instead of the longest, and could miss the overall longest
  3. It would count some subarrays twice
  4. It would crash on negative numbers
Show the answer

B. It would find the shortest qualifying subarray ending at each jj instead of the longest, and could miss the overall longest

For a fixed right end jj, the subarray a[i..j−1]a[i..j-1] is longest when ii is the earliest index with P[i]=P[j]−kP[i]=P[j]-k. Keeping the latest index gives the shortest one. On the bit example the overwrite version never pairs P[10]=2P[10]=2 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 jj is P[j]−min⁡i<jP[i]P[j]-\min_{i<j}P[i]: subtract the smallest earlier prefix. Keep a running minimum of PP.
  • Dynamic programming. Let E[j]E[j] be the best sum of a subarray ending at jj. Such a subarray is either a[j]a[j] alone or a subarray ending at j−1j-1 extended by a[j]a[j], so E[j]=max⁡(a[j], E[j−1]+a[j])E[j]=\max\big(a[j],\ E[j-1]+a[j]\big): extend or restart.
DerivationCorrectness, and why linear time is optimal
  1. E[0]=a[0],E[j]=a[j]+max⁡(E[j−1], 0)E[0]=a[0],\qquad E[j]=a[j]+\max\big(E[j-1],\,0\big)

    The recurrence is exhaustive: every non-empty subarray ending at jj is either the single element or ends at j−1j-1 before a[j]a[j] is appended, so

  2. max⁡0≤j<nE[j],E[j]=P[j+1]−min⁡0≤i≤jP[i]\max_{0\le j<n}E[j],\qquad E[j]=P[j+1]-\min_{0\le i\le j}P[i]

    Every subarray ends somewhere, so the answer is the best E[j]E[j]. Unrolling the recurrence links it to the prefix view:

  3. T(n)=Θ(n)T(n)=\Theta(n)

    Lower bound. Any correct algorithm reads all nn entries: if it never reads a[i]a[i], set a[i]a[i] larger than the sum of the absolute values of all the others. Then the true answer includes a[i]a[i] and changes with it, while the algorithm's output cannot. So Ω(n)\Omega(n) in every model, and the scan is optimal.

python
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.

Predict before you look

Run the non-empty version on [2,−5,4,−1,2,−6,5,−2,3,−4][2,-5,4,-1,2,-6,5,-2,3,-4]. What is the largest value cur reaches before index 6, that is, over a[0..5]a[0..5]?

Show the answer

5

cur takes the values 2,−3,4,3,5,−12,-3,4,3,5,-1 on a[0..5]a[0..5]: it restarts at 44 and extends through −1-1 and 22 to 55, the sum of a[2..4]a[2..4]. Then −6-6 drops it to −1-1, it restarts at 55, and the overall best becomes 5−2+3=65-2+3=6, from a[6..8]a[6..8].

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 00, the sum of an empty subarray.

python
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 end

With a length limit L≤j−i≤RL\le j-i\le R on the subarray a[i..j−1]a[i..j-1], the prefix view becomes max⁡j(P[j]−min⁡j−R≤i≤j−LP[i])\max_j\big(P[j]-\min_{j-R\le i\le j-L}P[i]\big): a minimum over a sliding window of the prefix array. A monotonic deque of candidate starts, with increasing prefix values, maintains it in O(1)O(1) amortized time per step, so the whole scan is O(n)O(n) (see Monotonic Queues in Dynamic Programming).

python
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 best

With L=1L=1 and R=nR=n 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 R×CR\times C matrix, fix the top and bottom rows, squash the band between them into one array of column sums, and run Kadane on it: O(R2C)O(R^2C), which is O(n3)O(n^3) for n×nn\times n. Compare O(n4)O(n^4) for trying every rectangle with a summed-area table, and O(n6)O(n^6) for summing every rectangle from scratch.

python
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]]))   # 7

The APSP conjecture of fine-grained complexity states that no O(n3−ε)O(n^{3-\varepsilon}) algorithm solves all-pairs shortest paths on nn-vertex graphs with integer weights polynomial in nn. If it holds, the O(n3)O(n^3) squash-and-Kadane algorithm is optimal up to no(1)n^{o(1)} factors. Smaller savings do exist: through the reduction to distance products, Williams's (2014) n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} algorithm for APSP solves the 2-D maximum subarray just as fast.

Notice the scale: the input has N=n2N=n^2 numbers, so the conjectured optimum is N3/2N^{3/2}, while the 1-D problem is linear. For NN arbitrary weighted points in the plane, the best box takes O(N2)O(N^2), and Backurs, Dikkala and Tzamos showed that N2−εN^{2-\varepsilon} would beat the best known max-weight clique algorithms.

Key takeaways

  • Subarrays with sum kk are pairs i<ji<j with P[i]=P[j]−kP[i]=P[j]-k; a hash map of prefix counts finds them all in one pass, O(n)O(n) expected, while without hashing deciding even k=0k=0 needs Ω(nlog⁡n)\Omega(n\log n) in the algebraic computation tree model.
  • Changing the key handles divisibility (remainders), balance (0↦−10\mapsto-1) and XOR; storing first or last indices gives longest or shortest subarrays.
  • Kadane's algorithm is "extend or restart", E[j]=max⁡(a[j],E[j−1]+a[j])E[j]=\max(a[j],E[j-1]+a[j]), 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 O(n)O(n).
  • The 2-D maximum subarray takes O(n3)O(n^3) 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.

Question 1

When counting subarrays with sum kk, why does the hash map store how many times each prefix value occurred, rather than just whether it occurred?

  1. Because one right end jj can close several qualifying subarrays at once, one for each earlier ii with P[i]=P[j]−kP[i]=P[j]-k
  2. To handle negative numbers, which make prefix sums decrease
  3. To find the longest subarray
  4. Because hash maps cannot store booleans efficiently
Show the answer

A. Because one right end jj can close several qualifying subarrays at once, one for each earlier ii with P[i]=P[j]−kP[i]=P[j]-k

Repeated prefix values mean repeated starts. In [3,4,−7,1,3,3,1,−4][3,4,-7,1,3,3,1,-4] with k=7k=7, the value 00 occurs at i=0i=0 and i=3i=3, so j=6j=6 closes two subarrays.

Question 2

A problem asks for the maximum sum of a non-empty subarray of [−3,−1,−2][-3,-1,-2]. A solution initializes best = cur = 0 and updates cur = max(0, cur + x). What does it return, and what is correct?

  1. It returns −1-1, which is correct
  2. It returns 00, but the correct answer is −1-1
  3. It returns −6-6, but the correct answer is −1-1
  4. It returns 00, which is correct
Show the answer

B. It returns 00, but the correct answer is −1-1

That code implements the convention where the empty subarray (sum 00) is allowed. With non-empty subarrays only, the best is the largest element, −1-1; initialize with a[0]a[0] and use max⁡(x, cur+x)\max(x,\ cur+x).

Question 3

Suppose someone finds an O(n2.9)O(n^{2.9}) algorithm for the maximum-sum rectangle in an n×nn\times n matrix of integers. What would follow?

  1. Nothing in particular; the O(n3)O(n^3) algorithm was never claimed to be optimal
  2. P would equal NP
  3. A truly subcubic algorithm for all-pairs shortest paths, refuting the APSP conjecture
  4. 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 O(n3−ε)O(n^{3-\varepsilon}) algorithm for the n×nn\times n maximum subarray gives an O(n3−ε/10)O(n^{3-\varepsilon/10}) algorithm for APSP. Together with the reduction in the other direction (Tamaki & Tokuyama, 1998), the two problems are subcubic-equivalent.

Question 4

The circular maximum subarray is computed as max⁡(Kadane, total−minimum subarray)\max(\text{Kadane},\ \text{total}-\text{minimum subarray}). On [−4,−2,−7][-4,-2,-7], why must the code return Kadane's answer directly?

  1. Because the total is negative, so subtraction overflows
  2. Because the minimum subarray is the whole array, so total minus it is 00, the sum of an empty subarray
  3. Because Kadane's algorithm fails on circular arrays
  4. It need not: the formula already returns −2-2
Show the answer

B. Because the minimum subarray is the whole array, so total minus it is 00, 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 −13−(−13)=0-13-(-13)=0, which corresponds to no subarray at all. The correct answer is the best non-empty subarray, −2-2.

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).