Skip to content

Longest Substring Without Repeating Characters

MediumLeetCode #3Time O(n)Space O(k)

Given a string, return the length of its longest substring (contiguous, not a subsequence) in which every character is distinct.

s = "abcabcbb" -> 3 ("abc")

Brute force checks every substring for duplicates, which is O(n²) or worse. The waste is that when you extend a valid substring by one character, almost everything is already known to be unique.

Use a window [left, right] that is always duplicate-free. Move right one step at a time. If the new character already appeared inside the window, the window is broken, so move left to just after that earlier copy. Storing each character’s last index in a map lets left jump in one step instead of shrinking one character at a time.

Show solutionHide solution
def length_of_longest_substring(s: str) -> int:
last_seen = {} # char -> index of its latest occurrence
left = 0
best = 0
for right, ch in enumerate(s):
if last_seen.get(ch, -1) >= left: # duplicate inside the window
left = last_seen[ch] + 1 # jump just past it
last_seen[ch] = right
best = max(best, right - left + 1)
return best
  • Time: O(n) — right visits each character once, and left only moves forward.
  • Space: O(k) — the map holds at most one entry per distinct character, where k is the alphabet size (at most n).
  • Only react to duplicates inside the window. In "abba", when the final a arrives its old index 0 is already left of left. Without the >= left check, left jumps backwards and the answer comes out as 3 instead of 2.
  • Window length is right - left + 1. Off-by-one here is the most common slip.
  • The empty string returns 0. The loop never runs, so best stays 0. No special case needed.

Longest Repeating Character Replacement (LeetCode 424)

Section titled “Longest Repeating Character Replacement (LeetCode 424)”

Replace at most k characters to get the longest run of one letter. The trick: a window is valid when window size - count of its most frequent char <= k. Keep a frequency count and shrink only when that fails.

Does s2 contain a permutation of s1? The trick: a fixed-size window of length len(s1) with a letter-count comparison. Slide it one step at a time, adding the new character and removing the old one.

Shortest subarray of positive numbers with sum at least target. The trick: grow right, and while the sum is big enough, record the length and shrink left. This works because all numbers are positive.