Problem 340617 · medium · Phase 03 Linear Management & Searching

Longest Substring Without Repeating Characters

sliding window · hash map · strings

Not every window has a fixed size. A variable-size sliding window expands while some rule holds and shrinks from the left the moment it breaks. Because each index enters and leaves the window at most once, the total work is O(n).

Given a string s, return the length of the longest substring that contains no repeated characters.

Examples

Input:  s = "abcabcbb"
Output: 3
Explanation: "abc" is the longest such substring.
Input:  s = "pwwkew"
Output: 3
Explanation: "wke" (note "pwke" is a subsequence, not a substring).
Input:  s = ""
Output: 0

Constraints

  • 0 <= len(s) <= 10**4
  • s may contain letters, digits, spaces and symbols.
  • Aim for O(n) time.

Goals

  • Grow a variable-size window on the right and shrink it on the left when a rule is broken
  • Use a set or dict to know in O(1) whether the window contains a character
  • Track the best window length while the window changes size
Starting Python…