Skip to content

Longest Substring Without Repeating Characters

Find the longest stretch of a string with no repeated character, using a window and last-seen positions.

MediumSliding Window
Solve on LeetCode

The problem

You get a string s that can contain English letters, digits, symbols and spaces. Return the length of the longest substring, meaning a contiguous run of characters, in which no character appears twice.

Input s = "chennai"

Output 4

"chen" has four different letters; adding the next n would repeat one.

Input s = "abba"

Output 2

When the last a arrives, the window already starts after the first a, so its start must not jump back.

Key constraint: The string can be up to 50,000 characters, so checking every substring is far too slow.

How to spot the pattern

  • You want the longest contiguous stretch that follows a rule: no repeats.
  • When the rule breaks, you can repair it by moving the left edge forward instead of starting over.

The idea

Keep a window [left, right] with no repeated characters, and grow it one character at a time. Remember the last index where each character appeared. When the new character was last seen inside the window, jump left to just past that index, which removes the repeat in one move, and then measure the window.

Brute force: Extend every start with a set until a character repeats, which takes O(n * m) time for an alphabet of m characters, or O(n^3) if you check each substring from scratch.

Step by step

  1. 1Keep a map from each character to its last index (for ASCII, an array of 128 slots works too), with left = 0 and best = 0.
  2. 2For each right, look up the last index of s[right].
  3. 3If that index is at or after left, move left to that index plus 1.
  4. 4Store right as the new last index of s[right].
  5. 5Update best with the window length right - left + 1.

See the pattern move

The sliding window pattern on a small example. Step through it, or press play.

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        last = {}  # character -> last index where it appeared
        left = 0
        best = 0
        for right, ch in enumerate(s):
            if ch in last and last[ch] >= left:
                left = last[ch] + 1  # jump past the earlier copy
            last[ch] = right
            best = max(best, right - left + 1)
        return best

Complexity

Time

O(n)

Space

O(m)

right visits each character once and left only jumps forward; the map holds one entry per distinct character, so m is the alphabet size.

Watch out for

  • Moving left backward: in "abba" the last a was seen at index 0, before the window starts, so left must stay where it is. Only jump when the last index is inside the window.
  • Measuring the window as right - left instead of right - left + 1.
  • Assuming only lowercase letters: the input can hold digits, symbols and spaces, so 26 slots are not enough.

Follow-up questions

What if at most k distinct characters are allowed in the window?

Keep a count for each character in the window, and shrink from the left while the window holds more than k distinct characters. That grow-then-shrink loop is the general sliding window template.

Why is this O(n) when there is a jump inside a loop?

left never moves back, and each jump is a single assignment, so the whole run does one step per character plus O(1) work per jump.

In Hinglish

Window mein har character ek hi baar. Repeat aaye toh left ko us character ki pichhli position ke aage le jao, peeche kabhi nahi.

Related problems