DevPath

← All problems

Longest Substring Without Repeating Characters

Medium strings · sliding-window

Description

Return the length of the longest substring that contains no repeated character.

Constraints

0 <= length <= 100000

Examples

Input: s = "abcabcbb"

Output: 3

"abc"

Hints (1)
  • Expand a window; when a repeat appears, move the left edge past the previous occurrence.

Solutions

Sliding window with last-seen index per character. · Time O(n) · Space O(min(n,alphabet))

func lengthOfLongestSubstring(s string) int {
    last := map[byte]int{}
    start, best := 0, 0
    for i := 0; i < len(s); i++ {
        if j, ok := last[s[i]]; ok && j >= start {
            start = j + 1
        }
        last[s[i]] = i
        if i-start+1 > best {
            best = i - start + 1
        }
    }
    return best
}

Create a free account to submit solutions, track progress and save problems.

Create account