2dbi

Longest Substring Without Repeating Characters

viaLeetCode

Problem Find the length of the longest substring of s with no repeated characters.

Input / Output

  • Input: string s. Output: max length.

Constraints

  • |s| up to 5*10^4; O(n) expected.

Example

  • "abcabcbb" → 3 ("abc"); "bbbbb" → 1; "pwwkew" → 3 ("wke" — substring, not subsequence).

Expected approach

  • Sliding window with last-seen-index map: for each right index, if s[r] was seen inside the current window, jump left to lastSeen[s[r]] + 1 (never move left backwards — the max() guard is the classic bug); update the answer each step. O(n) time, O(alphabet) space. The count-map + shrink-loop variant is equivalent; the index-jump version avoids the inner loop.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account