Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Counting Subarrays with Windows

“At most k” minus “at most k − 1”, and when windows fail.

How many subarrays of a million numbers contain at most two distinct values? There can be about 5×10115\times10^{11} of them, yet one window pass counts them all, because for each right end the valid left ends form a single block that the window already knows. The same structure turns "exactly kk" into a difference of two counts, and its absence tells you when to reach for prefix sums, monotonic stacks or merge sort instead.

What you’ll learn

  • Count all valid windows of a hereditary rule in O(n)O(n) as ∑r(r−lo(r)+1)\sum_r(r-\mathrm{lo}(r)+1), and of an upward-closed rule as ∑r(hi(r)+1)\sum_r(\mathrm{hi}(r)+1).
  • Prove that "exactly kk" equals "at most kk" minus "at most k−1k-1" for counts that grow with the window, and apply it to distinct values and odd numbers.
  • Count by contribution with previous occurrences and monotonic stacks: sums of distinct counts and of minima over all subarrays in O(n)O(n).
  • Recognize when windows fail, replace them with prefix sums and hash maps or merge-sort counting, and relate the hardest case to counting inversions.

One block of starts per right end

DerivationProof
  1. { l: a[l..r] valid }=[ lo(r), r ]⟹r−lo(r)+1 windows\{\,l:\ a[l..r]\ \text{valid}\,\}=[\,\mathrm{lo}(r),\,r\,]\quad\Longrightarrow\quad r-\mathrm{lo}(r)+1\ \text{windows}

    Count each valid window a[l..r]a[l..r] (inclusive) once, at its right end rr. For a hereditary rule the window theorem says the valid starts for rr form one block:

  2. { l: a[l..r] valid }=[ 0, hi(r) ]⟹hi(r)+1 windows\{\,l:\ a[l..r]\ \text{valid}\,\}=[\,0,\,\mathrm{hi}(r)\,]\quad\Longrightarrow\quad \mathrm{hi}(r)+1\ \text{windows}

    For an upward-closed rule, if a[l..r]a[l..r] is valid then so is a[l′..r]a[l'..r] for every l′<ll'<l, a super-window. The valid starts form the block [0,hi(r)][0,\mathrm{hi}(r)]:

  3. total=∑r=0n−1(r−Lr+1),L0≤L1≤⋯≤Ln−1\text{total}=\sum_{r=0}^{n-1}\big(r-L_r+1\big),\qquad L_0\le L_1\le\cdots\le L_{n-1}

    The window pass maintains L=lo(r)L=\mathrm{lo}(r) (or hi(r)\mathrm{hi}(r)) for every rr, because both are non-decreasing in rr. Adding one term per rr costs nothing extra:

python
from collections import defaultdict

def count_at_most_k_distinct(a, k):
    """Number of subarrays a[l..r] with at most k distinct values (k >= 0)."""
    count = defaultdict(int)
    L = total = 0
    for R, x in enumerate(a):
        count[x] += 1
        while len(count) > k:
            count[a[L]] -= 1
            if count[a[L]] == 0:
                del count[a[L]]
            L += 1
        total += R - L + 1             # every start in [L, R] is valid for this R
    return total

print(count_at_most_k_distinct([1, 2, 1, 2, 3], 2))   # 12

O(n)O(n) expected time with a hash map. The loop is the longest-window template with one changed line: it adds R−L+1R-L+1 instead of taking a maximum.

Predict before you look

How many of the 15 subarrays of [1,2,1,2,3][1,2,1,2,3] contain at most 2 distinct values?

Show the answer

12

For R=0,1,2,3R=0,1,2,3 the window starts at L=0L=0 and adds 1+2+3+4=101+2+3+4=10. When the 3 enters at R=4R=4, the window must shrink to a[3..4]=[2,3]a[3..4]=[2,3] and adds 2. Total 12; the missing three, [1,2,1,2,3][1,2,1,2,3], [2,1,2,3][2,1,2,3] and [1,2,3][1,2,3], each hold three distinct values.

Any hereditary rule works the same way. Products of positive integers below KK: shrink while the product is at least KK, dividing by a[L]a[L] on the way out; for [3,4,2,5][3,4,2,5] and K=30K=30 the count is 8 of 10 (only [4,2,5][4,2,5] and the whole array reach 30). In C++, stop multiplying once the product reaches KK, or it overflows. Upward-closed rules such as "sum ≥S\ge S with positive values" count either directly with hi(r)+1\mathrm{hi}(r)+1 or as all n(n+1)/2n(n+1)/2 subarrays minus those with sum ≤S−1\le S-1, a hereditary count.

Exactly k = at most k − at most (k − 1)

DerivationProof
  1. W′⊆W ⟹ f(W′)≤f(W)≤kW'\subseteq W\ \Longrightarrow\ f(W')\le f(W)\le k

    Heredity. If W′⊆WW'\subseteq W then f(W′)≤f(W)f(W')\le f(W), so f(W)≤kf(W)\le k implies f(W′)≤kf(W')\le k.

  2. {f=k}={f≤k}∖{f≤k−1}⟹#{f=k}=A(k)−A(k−1)\{f=k\}=\{f\le k\}\setminus\{f\le k-1\}\quad\Longrightarrow\quad\#\{f=k\}=A(k)-A(k-1)

    Difference. The windows with f≤k−1f\le k-1 are among those with f≤kf\le k, and what remains has f=kf=k exactly:

python
def count_exactly_k_distinct(a, k):
    return count_at_most_k_distinct(a, k) - count_at_most_k_distinct(a, k - 1)

print(count_exactly_k_distinct([1, 2, 1, 2, 3], 2))   # 12 - 5 = 7

A(1)=5A(1)=5 here: no two neighbors are equal, so only the five single elements have one distinct value. Two passes, O(n)O(n) expected time; a single pass with two left pointers, one for each bound, adds Lk−1−LkL_{k-1}-L_k per step and gives the same count.

Think first Why can't one window count the subarrays with exactly kk distinct values directly, say by adding 1 whenever its current window has exactly kk?

"Exactly kk" is not hereditary: in [1,2,1,2,3][1,2,1,2,3] with k=2k=2, the window [1,2][1,2] qualifies but its sub-window [1][1] does not, so the valid starts for a fixed right end form a block in the middle, [lok(r), lok−1(r)−1][\mathrm{lo}_k(r),\ \mathrm{lo}_{k-1}(r)-1], not one that ends at rr. A single window sees only the left end of that block. Two pointers, one per bound, see both ends, which is the at-most difference in disguise.

When ff is additive, a sum of per-element indicators such as the number of odd elements, prefix sums give a second route: the number of odd values in a[i..j−1]a[i..j-1] is O[j]−O[i]O[j]-O[i] for prefix counts OO, and a hash map counts the pairs with difference kk in one pass, exactly like subarrays with sum kk. For [3,8,5,6,7,2][3,8,5,6,7,2] and k=2k=2 both methods give 6: two windows hold the odd values 3 and 5, and four hold 5 and 7.

python
def count_exactly_k_odd(a, k):
    """Subarrays with exactly k odd numbers, from prefix counts of odd numbers."""
    seen = defaultdict(int)
    seen[0] = 1                        # the empty prefix
    odd = total = 0
    for x in a:
        odd += x % 2
        total += seen[odd - k]         # earlier prefixes with k fewer odd numbers
        seen[odd] += 1
    return total

print(count_exactly_k_odd([3, 8, 5, 6, 7, 2], 2))   # 6

Counting by contribution

Some questions sum a quantity over all n(n+1)/2n(n+1)/2 subarrays: the total of their distinct counts, or of their minima. Rather than visiting subarrays, flip the sum: decide, for each position, in how many subarrays it is responsible for one unit, and make sure every unit is charged to exactly one position.

DerivationProof: charge each unit once
  1. prev(i)<l≤i≤r≤n−1 ⟹ (i−prev(i))(n−i) windows\mathrm{prev}(i)<l\le i\le r\le n-1\ \Longrightarrow\ \big(i-\mathrm{prev}(i)\big)(n-i)\ \text{windows}

    Distinct values. Charge each distinct value of a[l..r]a[l..r] to its first occurrence inside the window. Position ii is that first occurrence exactly when no earlier copy lies in the window:

  2. p(i)<l≤i≤r<q(i) ⟹ (i−p(i))(q(i)−i) windowsp(i)<l\le i\le r<q(i)\ \Longrightarrow\ \big(i-p(i)\big)\big(q(i)-i\big)\ \text{windows}

    Minima. Charge the minimum of a[l..r]a[l..r] to its rightmost occurrence. Position ii holds it exactly when everything in a[l..i−1]a[l..i-1] is ≥a[i]\ge a[i] and everything in a[i+1..r]a[i+1..r] is >a[i]>a[i], that is:

  3. each subarray is charged to exactly one i\text{each subarray is charged to exactly one } i

    The asymmetric tie rule, strict on the left and non-strict on the right, is what makes the charge unique when values repeat. Both pp and qq come from one monotonic-stack pass each, and prev\mathrm{prev} from a dictionary of last positions: O(n)O(n) in all.

python
def sum_subarray_minima(a):
    """Sum over all subarrays of their minimum, in O(n) with monotonic stacks."""
    n = len(a)
    left, right, st = [0] * n, [0] * n, []
    for i in range(n):                 # p(i): previous strictly smaller
        while st and a[st[-1]] >= a[i]:
            st.pop()
        left[i] = i - (st[-1] if st else -1)
        st.append(i)
    st = []
    for i in range(n - 1, -1, -1):     # q(i): next smaller or equal
        while st and a[st[-1]] > a[i]:
            st.pop()
        right[i] = (st[-1] if st else n) - i
        st.append(i)
    return sum(a[i] * left[i] * right[i] for i in range(n))

print(sum_subarray_minima([2, 4, 1, 3]))   # 4 + 4 + 6 + 3 = 17

For [2,4,1,3][2,4,1,3] the four positions are charged 2⋅1⋅22\cdot1\cdot2, 4⋅1⋅14\cdot1\cdot1, 1⋅3⋅21\cdot3\cdot2 and 3⋅1⋅13\cdot1\cdot1. The stacks are the ones of Monotonic Stacks & Queues; the same counts underlie Cartesian Trees & Nearest Smaller Values.

When windows fail, and what replaces them

Count the subarrays…Monotone?MethodTime
with at most / exactly kk distinct valuesat most: hereditarywindow; difference of two windowsO(n)O(n) expected
with max⁡−min⁡≤d\max-\min\le dhereditarywindow with two monotonic dequesO(n)O(n)
with sum exactly kk, negatives allowednoprefix sums and a hash map of countsO(n)O(n) expected
with sum ≤S\le S, negatives allowednocount pairs i<ji<j with P[j]−P[i]≤SP[j]-P[i]\le S by merge sort or a Fenwick treeO(nlog⁡n)O(n\log n)
weighted by their minimum or distinct count—contribution countingO(n)O(n)
Prefix sums P[0]=0P[0]=0, P[i+1]=P[i]+a[i]P[i+1]=P[i]+a[i] turn subarray questions into questions about pairs of prefixes.
python
def count_sum_at_most(a, S):
    """Subarrays with sum <= S, any integers: pairs i < j with P[j] - P[i] <= S, by merge sort."""
    P = [0]
    for x in a:
        P.append(P[-1] + x)

    def sort_count(lo, hi):            # sorts P[lo:hi] and returns the pairs inside it
        if hi - lo <= 1:
            return 0
        mid = (lo + hi) // 2
        c = sort_count(lo, mid) + sort_count(mid, hi)
        i = lo
        for j in range(mid, hi):       # both halves sorted: count left P[i] >= P[j] - S
            while i < mid and P[i] < P[j] - S:
                i += 1
            c += mid - i
        P[lo:hi] = sorted(P[lo:hi])    # merge the halves (the sort finds the two runs)
        return c

    return sort_count(0, len(P))

print(count_sum_at_most([5, -10, 3], 0))   # 4: [-10], [5, -10], [-10, 3], [5, -10, 3]

The pairs that straddle the middle are counted by a two-pointer pass over two sorted halves, the same staircase walk as pair sum: T(n)=2T(n/2)+O(n)=O(nlog⁡n)T(n)=2T(n/2)+O(n)=O(n\log n).

Check your understanding

You must count the subarrays with sum at most SS in an array of 10510^5 integers, some negative. Which method is correct and fast?

  1. The counting window, adding R−L+1R-L+1 after shrinking while the sum exceeds SS
  2. Prefix sums with a hash map of exact prefix values
  3. Count the pairs i<ji<j with P[i]≥P[j]−SP[i]\ge P[j]-S using merge sort or a Fenwick tree over compressed prefix values
  4. Sort the array and use two pointers
Show the answer

C. Count the pairs i<ji<j with P[i]≥P[j]−SP[i]\ge P[j]-S using merge sort or a Fenwick tree over compressed prefix values

With negatives the rule is not hereditary, so a window undercounts or overcounts. Each subarray is a pair of prefixes, and the condition P[i]≥P[j]−SP[i]\ge P[j]-S is a comparison, counted for all pairs in O(nlog⁡n)O(n\log n).

Key takeaways

  • For a hereditary rule the valid windows ending at rr form the block [lo(r),r][\mathrm{lo}(r),r], so one window pass counts all of them as ∑r(r−lo(r)+1)\sum_r(r-\mathrm{lo}(r)+1); upward-closed rules count ∑r(hi(r)+1)\sum_r(\mathrm{hi}(r)+1).
  • If a count ff only grows with the window, "exactly kk" is A(k)−A(k−1)A(k)-A(k-1); additive counts such as odd numbers also fall to prefix sums with a hash map.
  • Contribution counting charges each subarray to one position: (i−prev(i))(n−i)(i-\mathrm{prev}(i))(n-i) for distinct values, monotonic stacks with an asymmetric tie rule for minima, O(n)O(n) in all.
  • Non-monotone rules need other tools: a hash map of prefix counts for exact sums, merge-sort or Fenwick counting for sums at most SS, a problem exactly as hard as counting inversions.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A counting window for "at most kk distinct values" has just shrunk, and the window is a[4..9]a[4..9] with R=9R=9. How much does it add to the total?

  1. 1
  2. 6
  3. 10
  4. 21
Show the answer

B. 6

The valid windows ending at index 9 start anywhere in [4,9][4,9]: 9−4+1=69-4+1=6 of them. Windows that end earlier were counted at their own right ends.

Question 2

For some array, 40 subarrays have at most 3 distinct values and 25 have at most 2. How many have exactly 3?

  1. 65
  2. 40
  3. 15
  4. It cannot be determined from these numbers
Show the answer

C. 15

Every subarray with at most 2 distinct values also has at most 3, so the 25 are inside the 40, and the remaining 40−25=1540-25=15 have exactly 3.

Question 3

In [5,5][5,5], contribution counting for minima uses pp = previous strictly smaller and qq = next smaller-or-equal. How many subarrays are charged to position 0 and to position 1?

  1. 1 and 2
  2. 2 and 2
  3. 1 and 1
  4. 2 and 1
Show the answer

A. 1 and 2

Position 0 has p=−1p=-1, q=1q=1: charged 1⋅1=11\cdot1=1 subarray, [5][5] at index 0. Position 1 has p=−1p=-1, q=2q=2: charged 2⋅1=22\cdot1=2, namely [5,5][5,5] and [5][5] at index 1. All three subarrays are charged exactly once, each to its rightmost minimum.

Question 4

Counting the subarrays with sum at most 0 in an array that may contain negative numbers is equivalent to which problem?

  1. Sorting the array
  2. Counting the non-strict inversions of the prefix-sum sequence
  3. 3SUM
  4. Finding the longest increasing subsequence
Show the answer

B. Counting the non-strict inversions of the prefix-sum sequence

A subarray a[i..j−1]a[i..j-1] has sum ≤0\le0 exactly when P[i]≥P[j]P[i]\ge P[j] with i<ji<j, and every integer sequence is a prefix-sum sequence up to a shift. So the two counts transfer both ways in O(n)O(n).

Further reading

  • A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 8 (amortized analysis: two pointers and nearest smaller elements).
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022): counting inversions by merge sort (chapter 2 problems).
  • P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.
  • T. M. Chan & M. Pătraşcu, "Counting inversions, offline orthogonal range counting, and related problems," SODA 2010.