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 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 " 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 as , and of an upward-closed rule as .
- Prove that "exactly " equals "at most " minus "at most " 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 .
- 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
Count each valid window (inclusive) once, at its right end . For a hereditary rule the window theorem says the valid starts for form one block:
For an upward-closed rule, if is valid then so is for every , a super-window. The valid starts form the block :
The window pass maintains (or ) for every , because both are non-decreasing in . Adding one term per costs nothing extra:
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)) # 12expected time with a hash map. The loop is the longest-window template with one changed line: it adds instead of taking a maximum.
How many of the 15 subarrays of contain at most 2 distinct values?
Show the answer
12
For the window starts at and adds . When the 3 enters at , the window must shrink to and adds 2. Total 12; the missing three, , and , each hold three distinct values.
Any hereditary rule works the same way. Products of positive integers below : shrink while the product is at least , dividing by on the way out; for and the count is 8 of 10 (only and the whole array reach 30). In C++, stop multiplying once the product reaches , or it overflows. Upward-closed rules such as "sum with positive values" count either directly with or as all subarrays minus those with sum , a hereditary count.
Exactly k = at most k − at most (k − 1)
Heredity. If then , so implies .
Difference. The windows with are among those with , and what remains has exactly:
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 = 7here: no two neighbors are equal, so only the five single elements have one distinct value. Two passes, expected time; a single pass with two left pointers, one for each bound, adds per step and gives the same count.
Think first Why can't one window count the subarrays with exactly distinct values directly, say by adding 1 whenever its current window has exactly ?
"Exactly " is not hereditary: in with , the window qualifies but its sub-window does not, so the valid starts for a fixed right end form a block in the middle, , not one that ends at . 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 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 is for prefix counts , and a hash map counts the pairs with difference in one pass, exactly like subarrays with sum . For and both methods give 6: two windows hold the odd values 3 and 5, and four hold 5 and 7.
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)) # 6Counting by contribution
Some questions sum a quantity over all 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.
Distinct values. Charge each distinct value of to its first occurrence inside the window. Position is that first occurrence exactly when no earlier copy lies in the window:
Minima. Charge the minimum of to its rightmost occurrence. Position holds it exactly when everything in is and everything in is , that is:
The asymmetric tie rule, strict on the left and non-strict on the right, is what makes the charge unique when values repeat. Both and come from one monotonic-stack pass each, and from a dictionary of last positions: in all.
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 = 17For the four positions are charged , , and . 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? | Method | Time |
|---|---|---|---|
| with at most / exactly distinct values | at most: hereditary | window; difference of two windows | expected |
| with | hereditary | window with two monotonic deques | |
| with sum exactly , negatives allowed | no | prefix sums and a hash map of counts | expected |
| with sum , negatives allowed | no | count pairs with by merge sort or a Fenwick tree | |
| weighted by their minimum or distinct count | — | contribution counting |
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: .
You must count the subarrays with sum at most in an array of integers, some negative. Which method is correct and fast?
- The counting window, adding after shrinking while the sum exceeds
- Prefix sums with a hash map of exact prefix values
- Count the pairs with using merge sort or a Fenwick tree over compressed prefix values
- Sort the array and use two pointers
Show the answer
C. Count the pairs with 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 is a comparison, counted for all pairs in .
Key takeaways
- For a hereditary rule the valid windows ending at form the block , so one window pass counts all of them as ; upward-closed rules count .
- If a count only grows with the window, "exactly " is ; additive counts such as odd numbers also fall to prefix sums with a hash map.
- Contribution counting charges each subarray to one position: for distinct values, monotonic stacks with an asymmetric tie rule for minima, 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 , 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.
A counting window for "at most distinct values" has just shrunk, and the window is with . How much does it add to the total?
- 1
- 6
- 10
- 21
Show the answer
B. 6
The valid windows ending at index 9 start anywhere in : of them. Windows that end earlier were counted at their own right ends.
For some array, 40 subarrays have at most 3 distinct values and 25 have at most 2. How many have exactly 3?
- 65
- 40
- 15
- 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 have exactly 3.
In , contribution counting for minima uses = previous strictly smaller and = next smaller-or-equal. How many subarrays are charged to position 0 and to position 1?
- 1 and 2
- 2 and 2
- 1 and 1
- 2 and 1
Show the answer
A. 1 and 2
Position 0 has , : charged subarray, at index 0. Position 1 has , : charged , namely and at index 1. All three subarrays are charged exactly once, each to its rightmost minimum.
Counting the subarrays with sum at most 0 in an array that may contain negative numbers is equivalent to which problem?
- Sorting the array
- Counting the non-strict inversions of the prefix-sum sequence
- 3SUM
- Finding the longest increasing subsequence
Show the answer
B. Counting the non-strict inversions of the prefix-sum sequence
A subarray has sum exactly when with , and every integer sequence is a prefix-sum sequence up to a shift. So the two counts transfer both ways in .
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.