Counting with "at most K" minus "at most K−1"

Video lessonComing soon

1 Counting every window

The last lesson's window found the longest stretch that follows a rule. Some problems ask a different question: how many stretches follow it? Here we want the number of subarrays with exactly K different values, with K = 2:

1021121334
nums. K = 2

The answer is 7: [1, 2], [1, 2, 1], [1, 2, 1, 1], [2, 1], [2, 1, 1], [1, 1, 3] and [1, 3].

The first code most of us write tries every start, and grows a set of values from each one. That is about n²/2 windows. At n = 10⁵ it is around 5 × 10⁹ steps. At about 10⁸ steps a second, that is far past the time limit, so it gets Time Limit Exceeded (TLE).

The sliding window takes one pass, but it cannot count "exactly K" directly. This lesson shows why, and the way around it. We count the windows with at most K different values, which a window can do, and take away the ones with at most K − 1.

2 Why one window cannot count exactly K

We write every window in the grid from the last lesson. The row is the start l, the column is the end r, and each cell holds how many different values that window has. The orange row and column hold the indexes.

Exactly 2 different values on the grid
l/r0123401222311223211231241
Grow from l = 0: 1, then 2, 2, 2, then 3

The window in the last lesson worked because a broken window stays broken as it grows. "Exactly 2" can fail in two ways. A window with too many values stays broken as it grows. But a window with too few can grow into a good one: [1] at index 0 grows into [1, 2].

So the good cells in a column do not run down to the diagonal. They form a band, with too many above it and too few below it. In column 4, the band is rows 2 and 3. Row 4 is the window [3], with only 1 value.

A shrink stops at the top of the band, at l = 2. Counting from there down to the diagonal gives three windows, and only two of them are good. One left end can mark where the band starts, but not where it stops.

3 Counting the windows with at most K

"At most 2 different values" is a rule the window handles. A window with 3 different values stays broken as it grows, so the grow-then-shrink loop from the last lesson works unchanged. The window keeps a count map, and the map's size is the number of different values.

The change is in what we record. After the shrink, the window from l to r is valid. Every shorter window that ends at r sits inside it, so it has no more different values, and it is valid too. Every window that starts before l is broken. That is why l moved past it. Here are all the windows that end at index 4:

121132113113133
Every window that ends at 4, one row per start. Orange has 3 values

So exactly r - l + 1 valid windows end at r, one for each start from l to r. On the grid, they are the run in column r from row l down to the diagonal. The last lesson recorded only the top cell of that run. Now we add the whole run:

windows += r − l + 1

Here is the full run with K = 2. The box on the right holds the map's size and the count so far:

Counting windows with at most 2 different values
1021121334l, r
nums
1different1windows
r = 0: 1 window ends here

So 13 windows have at most 2 different values. They are every cell of the grid except the two 3s.

4 Exactly K is at most K minus at most K − 1

The windows with exactly 2 different values are the windows with at most 2, minus the windows with at most 1. The grid shows it:

Exactly 2 = at most 2 − at most 1
l/r0123401222311223211231241
At most 2: 13 windows

In each column, both runs reach down to the diagonal. So the at-most-1 run is the bottom part of the at-most-2 run. Taking it away leaves the band from section 2. One window could not find the band, but two windows find its top and its bottom.

exactly(K) = atMost(K) − atMost(K−1)

The two passes side by side, with the left end each one stops at after the shrink:

rl, at most 2addsl, at most 1addsexactly 2
001010
102111
203212
304222
423412
1367

The last column is the band in each column of the grid. At r = 4, the at-most-2 window stops at l = 2, and the at-most-1 window stops at l = 4. So the good starts are 2 and 3.

5 The code and the cost

One helper, atMost, runs the loop from section 3. The answer calls it twice. The helper returns 0 when K is negative, because no window has fewer than 0 values. Section 7 shows why that line matters.

C++

windows is a long long. The count can reach about 5 × 10⁹, more than an int holds. counts.size() counts every key, so a value whose count falls to 0 must be erased.

windows is a long. The count can reach about 5 × 10⁹, more than an int holds. A key whose count falls to 0 stays in the map until we remove it.

Nothing to watch for size. Python's integers grow as needed. A key whose count falls to 0 stays in the dict until we del it.

Nothing to watch for size. Numbers stay exact up to about 9 × 10¹⁵, so a count of 5 × 10⁹ is safe. A key whose count falls to 0 stays in the Map until we delete it.

The count is an int64. int is 64 bits on today's machines too, but the return type makes it plain. A key whose count falls to 0 stays in the map until we delete it.

Write r + 1 - l, not r - l + 1. When K is 0, the shrink empties the window, l becomes r + 1, and r - l on a usize underflows. The count is an i64, because it can reach about 5 × 10⁹.

windows is a long. The count can reach about 5 × 10⁹, more than an int holds. A key whose count falls to 0 stays in the dictionary until we remove it.

On our array, every tab returns 7 for K = 2, 6 for K = 1, 2 for K = 3 and 0 for K = 0.

Each call to atMost is one sliding-window pass. r moves n times, l moves at most n times, and each map step is O(1) on average. Two calls make about 4n steps, so the time is O(n). At n = 10⁵, that is around 4 × 10⁵ steps instead of 5 × 10⁹. The map holds at most K + 1 values at a time, so the extra space is O(K), and never more than O(n).

6 At least K

Some problems ask for windows with at least K. Those are all the windows, minus the ones with at most K − 1. An array of n values has n(n + 1)/2 windows, so:

atLeast(K) = n(n+1)/2 − atMost(K−1)

On our array, that is 15 − 6 = 9 windows with at least 2 different values.

There is also a direct way, from the shortest-window loop of the last lesson. Here a window is good when it has at least K different values. A good window stays good as it grows. So when the window from l to r is good, the windows from l to every later end are good too. That is n - r windows that start at l. We add them, and then nums[l] leaves:

windows = 0
for r from 0 to n − 1:
    add nums[r]
    while the window is good:
        windows += n − r
        remove nums[l], move l right

On the grid, this counts by rows instead of columns. Each row counts from its first good cell to the end:

l/r0123401222311223211231241
At least 2: rows add 4, 3, 1, 1 and 0. That is 9

This form suits rules that a window meets once it holds enough, such as "holds every letter of a set at least once".

7 Mistakes and edge cases

  • K − 1 when K is 0. atMost(-1) asks for windows with fewer than 0 values. Even an empty window has more than −1 values, so the shrink never stops. l runs past the end of the array, and the program gets a Runtime Error. Any input with K = 0 shows it, such as a sum of 0 in an array of 0s and 1s. The k < 0 check at the top of the helper prevents it.
  • Adding 1 for each r. That counts only the longest window that ends at r. On our array, both passes then give 5, and the answer comes out as 0 instead of 7.
  • A 32-bit count. When every value is the same and K = 1, every window counts. At n = 10⁵ there are about 5 × 10⁹ of them, and a 32-bit int holds only about 2 × 10⁹.
  • Keeping map entries at 0. The map's size then counts values that have left. With K = 1, the size never drops below 2 once a second value has entered, and l runs off the array.

8 When to use it

The sign is a question about how many subarrays or substrings meet a rule, not which one is longest. Then we check the rule:

  • At most K. A broken window stays broken as it grows. Run the window and add r - l + 1 for each r.
  • Exactly K. Count at most K, then take away at most K − 1.
  • At least K. Take at most K − 1 away from all n(n + 1)/2 windows, or add n - r for each l.

The loop stays the same for every rule. Only the state changes:

The rule countsWhat the window keeps
Different valuesa count map, whose size is the number of values
Odd numbershow many odd values it holds
1s in an array of 0s and 1sits sum

The prefix sums lesson counted subarrays with a sum of exactly k using a running-sum map. That map works with negative values, where a window fails. This lesson's trick works for counts the map cannot track, such as the number of different values.

When "exactly K" will not slide, ask whether "at most K" does. If it does, run it twice and subtract.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.