awelgorithms

Invalid window still has a defined state

Updated

When the constraint fails, L, R, sum, counts, and distinct are still the numbers for a[L..R]. Invalid means do not record as answer, not wipe the state.

What to focus on

You shrink by using that defined state: subtract a[L], decrement cnt[a[L]], then L++. An undefined or null state cannot tell you what to drop.

Worked examples

sum too big

a = [4, 1, 9, 1], need sum ≤ 10, L=0 R=2
  1. sum is 14
  2. invalid as an answer
  3. drop a[0] using 14

Result: state 14, then shrink to 10

too many distinct

s = "abca", k=2, L=0 R=2
  1. "abc" distinct 3
  2. map {a:1,b:1,c:1} still exact
  3. drop s[0]

Result: distinct 3 is defined, then 2

too many zeros

a = [1, 0, 0, 1, 9], k=1 zeros, L=0 R=2
  1. zeros=2
  2. [1,0,0] invalid
  3. zeros counter is 2, drop a[0]

Result: zeros 2, then 2, then 1

Try it

Write printState(a, L, R). a is an array of integers, or s is a string. L is the left index. R is the right index. The window includes a[L..R] even when invalid. Invalid means do not record as answer. Print the state before shrinking. Return nothing. On [4, 1, 9, 1] stop at [0, 2] sum 14. Repeat for "abca" k=2 and [1, 0, 0, 1, 9] k=1 zeros.

a (or s) is nonempty. The current [L, R] is invalid for the window constraint but still a real slice.