awelgorithms

Length is discovered not given

Updated

Variable-length means k is not an input. Expand and shrink until the constraint decides the length. Length is R-L+1 of a valid window you found.

What to focus on

Window constraint: longest window with all unique values. You do not set k first. The constraint produces candidates. You measure them.

Worked examples

discover 3

s = "abca"
  1. abc unique length 3
  2. next a duplicates, shrink L to 1
  3. bca unique length 3

Result: best length 3 · never given k=3

discover 3 in array

a = [4, 1, 9, 1]
  1. [4,1,9] unique length 3
  2. next 1 duplicates
  3. shrink past the old 1

Result: best length 3

discover 1

a = [7]
  1. one cell is unique
  2. length 1 is measured, not passed in

Result: best length 1

Try it

Write longestUniqueLen(a). 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]. k is not an argument. Return the discovered length of the longest unique window. Do not print. On s="abca"; a=[4, 1, 9, 1]; a=[7].

a (or s) is nonempty.