Do not record an invalid window
Updated
If the constraint fails, skip the best-update. The window may still exist as state for the next shrink, but it is not a candidate.
What to focus on
Classic miss: recording length after every expand, including the step that just broke the constraint. Check first, record second.
Worked examples
sum 14
a = [4, 1, 9, 1], need sum ≤ 10, L=0 R=2- sum 14
- do not set best=3
Result: skip [0,2]
second a
s = "abca", unique, L=0 R=3- cnt[a]=2
- "abca" is not unique
- do not record 4
Result: skip [0,3]
two zeros
a = [1, 0, 0, 1, 9], k=1, L=0 R=2- zeros 2>1
- do not record length 3
Result: skip [0,2]
Try it
Write skipInvalid(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] but fails the constraint, so it is not a candidate. Print skip and keep the previous best. Show the bug if you record before the validity test. Return nothing. On [4, 1, 9, 1] [0, 2] sum 14; "abca" [0, 3]; [1, 0, 0, 1, 9] [0, 2] zeros 2.
a (or s) is nonempty. The current [L, R] is a real slice that fails the window constraint.