awelgorithms

Track the best valid bounds

Updated

When a valid window beats bestLen, save bestL and bestR (and the new length). The answer slice is a[bestL..bestR], not just a number.

What to focus on

Window constraint: longest window with all unique values. Update bounds at the same moment you update bestLen. Ties keep the first bounds.

Worked examples

first best

s = "abca"
  1. abc at L=0 R=2 length 3 → save (0,2)
  2. bca at L=1 R=3 length 3 ties, keep (0,2)

Result: bestL=0 bestR=2 · "abc"

array best

a = [4, 1, 9, 1]
  1. [4,1,9] at (0,2) length 3 → save (0,2)
  2. [9,1] at (2,3) length 2 loses

Result: bestL=0 bestR=2 · [4, 1, 9]

single cell

a = [7]
  1. (0,0) length 1 beats init 0
  2. save bestL=0 bestR=0

Result: bestL=0 bestR=0 · [7]

Try it

Write bestUniqueBounds(a). a is an array of integers, or s is a string. bestL and bestR are the saved bounds of the longest unique window, which includes a[bestL..bestR]. Ties keep the first. Return those bounds. On s="abca"; a=[4, 1, 9, 1]; a=[7].

a (or s) is nonempty.

LeetCode problems that use this skill