awelgorithms

Maintain counts inside the window

Updated

A count map tracks how many times each value appears in a[L..R] (or s[L..R]). Expand: cnt[x]++. Shrink: cnt[x]-- and drop the key at 0.

What to focus on

After every move, cnt[x] matches the slice. Never leave a 0-count key if you read distinct from map.size.

Worked examples

expand chars

s = "abca", L=0
  1. R=0 {a:1}
  2. R=1 {a:1, b:1}
  3. R=2 {a:1, b:1, c:1}
  4. R=3 {a:2, b:1, c:1}

Result: {a:2, b:1, c:1} on [0,3]

shrink first a

s = "abca", L=0 R=3, {a:2, b:1, c:1}
  1. drop s[0]='a'
  2. a:2→1
  3. L=1

Result: {a:1, b:1, c:1} on [1,3]

array values

a = [1, 2, 1, 3], expand all then drop a[0]
  1. {1:2, 2:1, 3:1}
  2. drop 1 → {1:1, 2:1, 3:1}

Result: {1:1, 2:1, 3:1} on [1,3]

Try it

Write windowCnt(s). s is a string, or a is an array of integers. L is the left index. R is the right index. The window includes s[L..R]. cnt[x] is how many times x appears in that slice. Expand "abca" then shrink once. Repeat on [1, 2, 1, 3]. Print the map after each move. Return nothing. After expand "abca" the map is {a:2, b:1, c:1}. After shrink it is {a:1, b:1, c:1}.

a (or s) is nonempty. Start with a real window [L, R].