All unique characters in the window
Updated
The invariant is cnt[ch]==1 for every character currently in s[L..R]. A count hitting 2 breaks uniqueness. Distinct equals the window length while the invariant holds.
What to focus on
Expand R. If s[R] was already in the window, shrink until that character's count is 1 again. Track max length among unique windows.
Worked examples
abca
s = "abca"- [0,2] "abc" all counts 1 len 3
- R=3 second a, cnt[a]=2
- drop s[0], cnt[a]=1, "bca" len 3
Result: best length 3
abcabcbb
s = "abcabcbb"- [0,2] "abc" len 3
- each later repeat shrinks L so counts return to 1
- final run of b is len 1
Result: best length 3
k distinct is different
a = [1, 2, 1, 3]- [0,2] has two 1s, not unique
- unique windows: [0,1], [1,2], [2,3] len 2
Result: best unique length 2
Try it
Write longestUnique(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]. Unique means every count is 1. Return the best unique length. On [1, 2, 1, 3] unique-all is not the same as at-most-2-distinct. "abca" and "abcabcbb" → 3. [1, 2, 1, 3] unique length 2.
s (or a) is nonempty.