learn deep. ship safe.Practice testsFollow ByteMunSubscribe

mediumStringsSliding windowHash map

Longest Substring Without Repeats

Find the length of the longest stretch of a string with no repeated characters. The go-to problem for practising the sliding-window technique.

By Tests checked by DeepakJavaScript or Python

Given a string s, return the length of the longest substring (a contiguous run of characters) in which no character appears more than once.

Characters are case-sensitive and spaces count as characters. A subsequence that skips characters doesn't count: the substring must be one unbroken piece of s. An empty string has length 0.

Examples

Example 1

Input: s = "abcabcbb"
Output: 3
Why: "abc" is the longest run without a repeat

Example 2

Input: s = "pwwkew"
Output: 3
Why: "wke"; note "pwke" is not contiguous

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s may contain letters, digits, symbols and spaces

Hints

Hint 1

Keep a window [start, i] that has no repeats. What should happen to start when s[i] is already in the window?

Hint 2

Store each character's last index. If it's inside the window, jump start to just after it.

Solution

Show the solution (try it yourself first)

Approach: a sliding window with last-seen indexes

Keep a window [start, i] that never contains a repeat, and a map of each character's most recent index. When s[i] was last seen inside the window, move start to just after that position. The condition last[ch] >= start matters: in "abba", when the final "a" arrives, its earlier position is already outside the window, and jumping back to it would wrongly shrink the window. After each step the window length is i - start + 1.

def longest_unique_substring(s):
    last = {}
    start = best = 0
    for i, ch in enumerate(s):
        if ch in last and last[ch] >= start:
            start = last[ch] + 1
        last[ch] = i
        best = max(best, i - start + 1)
    return best

Complexity

Time O(n): each index is processed once and start only moves forward. Space O(k), where k is the number of distinct characters.

Case 1Input: "abcabcbb"Expected: 3
Case 2Input: "pwwkew"Expected: 3

Run checks these 2 samples. Submit checks all 8 tests, including hidden ones.

  1. Group AnagramsStrings · Hash map · Sorting
    medium
  2. Pair with Target SumArrays · Hash map
    easy
  3. Balanced BracketsStack · Strings
    easy
  4. Palindrome SentenceStrings · Two pointers
    easy