awelgorithms

Restart is not the same as shrink

Updated

Shrink moves L forward and keeps R. The window stays a[L..R] with the same right edge. Restart throws the window away and starts at R (L = R).

What to focus on

Window constraint: longest unique window. Shrink drops left cells until the duplicate is gone and keeps the unique suffix. Restart discards that suffix. Kadane-style restart is a different move: it is correct for max sum, not for this unique window.

Worked examples

shrink keeps R

a = [4, 1, 9, 1], R=3 duplicate 1
  1. old 1 sits at index 1
  2. exclude until L=2
  3. R stays 3
  4. window [9,1] unique

Result: shrink → L=2 R=3 · length 2

restart loses the suffix

a = [4, 1, 9, 1], R=3 restart at R
  1. throw away [4,1,9]
  2. set L=3 R=3
  3. window [1] only

Result: restart → L=3 R=3 · length 1

string shrink vs restart

s = "abca", R=3 second a
  1. shrink L to 1 → "bca" length 3
  2. restart L=3 → "a" length 1

Result: shrink wins · keep R

Try it

Write uniqueAtR(a). a is an array of integers, or s is a string. R is the current right index that just introduced a duplicate still in [L, R]. Shrink moves L and keeps R. Restart sets L = R. Print both resulting windows. Shrink is the unique-window move. Return nothing. On [4, 1, 9, 1] at R=3; s="abca" at R=3.

a (or s) is nonempty. The current R introduces a duplicate of some value still in [L, R].