Back to the 100
Problem 056Sliding Window
Medium

Longest Substring Without Repeating Characters

056

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

EXAMPLES

Example 1
Input
{
  "s": "abcabcbb"
}

Output
3

FUNCTION SHAPE

s: stringint
SOLUTION NOTE

The function is monotonic: TTTFFFF. We check if the current character s[r] is already present in our window. If it is, increment the left pointer until we get rid of that previous instance.

Reveal reference solution +
pythonREFERENCE
def lengthOfLongestSubstring(self, s: str) -> int:
    n, l, res, freq = len(s), 0, 0, Counter()

    for r in range(n):
        freq[s[r]] += 1

        while freq[s[r]] >= 2:
            freq[s[l]] -= 1
            l += 1

        res = max(res, r - l + 1)

    return res
TimeO(n)
SpaceO(26) = O(1)
Open on LeetCode
00:00
3 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.