awelgorithms

Each index leaves the window once

Updated

L only increases. Index i is excluded at most once, when L steps off i. Together with one enter, that is at most one ++ and one -- per index for sum/counts.

What to focus on

Indices still inside at the end never leave during the scan (or you drain L after R=n-1 if you need them to). They still entered once.

Worked examples

drop 4

a = [4, 1, 9, 1], length-3 slide
  1. L 0→1 drops index 0 once
  2. index 1,2,3 still in [1,3]

Result: index 0 left once

unique drop

s = "abca"
  1. L 0→1 at the second a
  2. index 0 left once
  3. 1,2,3 remain

Result: one leave event

zeros two leaves

a = [1, 0, 0, 1, 9], k=1
  1. drop index 0 then 1 while R=2
  2. each of those L++ once

Result: indices 0 and 1 left once each

Try it

Write logLeave(a). a is an array of integers, or s is a string. L is the left index and only increases. Index i leaves at most once, when L steps off i. Print leave(i). No index should appear twice. Compare leave count ≤ n. On the length-3 slide of [4, 1, 9, 1], unique "abca", and [1, 0, 0, 1, 9] k=1.

a (or s) is nonempty. L only increases. 1 ≤ k ≤ n for the fixed-length slide.