Longest stretch without a repeat
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return the length of the longest substring of `s` in which no character appears twice. A substring is a run of neighboring characters: in `"pwwkew"` the answer is 3 (`"wke"`), not 4, because `"pwke"` skips a character. An empty string gives 0.
What this exercise teaches
The window always holds a stretch without repeats. A repeated character only matters if its earlier copy is still inside the window, which is why the start is set with Math.max: without it, an old position can drag the start backwards, as in abba.
A hint if you get stuck
Slide a window over the string. Remember the last index of every character in a `Map`. When the current character was last seen inside the window, move the start of the window to just after that position, and never move it backwards.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Strings and dates
- Make a URL slugFree
- Truncate with an ellipsisFree
- Format moneyFree
- Parse a query stringFree
- Align a text tableFree
- Add days to a dateFree
- Days between two datesFree
- Format a durationFree
- Last day of the monthFree
- Human readable file sizeFree
- Weekdays between two datesFree
- Convert to camelCaseFree
- Run-length encodingFree