Maintained by Vikas Dulgunde, software engineer
You are handed a string `s` that may contain letters, digits, symbols, or spaces. Your job is to find a contiguous slice of it where every character is distinct, and report how long the longest such slice can be.
The slice must be contiguous, so you cannot skip over characters and stitch the remaining ones together. Once a character would appear twice inside your current slice, that slice is no longer valid and the count for it stops.
Return only the length of the best slice, not the slice itself. An empty input has no characters, so the answer there is 0.
The slice "abc" has three distinct characters. Extending it to "abca" repeats 'a', so 3 is the most you can reach anywhere in the string.
"wke" is a valid window of length 3. "pww" fails because 'w' repeats, and no window beats 3.
When the second 'd' is reached, the window resets to start just after the first 'd', giving "vdf" of length 3 rather than collapsing all the way back to the start.
Visible test cases
Think about a window that expands to the right and only shrinks from the left when it has to. You never need to move the right edge backward.
When you read a character you have seen before, the left edge of the window cannot stay where it was. It must jump to just past that character's previous position.
Store the most recent index of each character. When a repeat shows up, advance the window start to that stored index plus one, but only forward, never backward.
Check every possible substring and keep the length of the longest one whose characters are all unique.
Keep one window over the string and remember the last position of every character. When a character repeats inside the window, slide the left edge forward in a single jump instead of re-scanning.