Longest Substring Without Repeating Characters
The problem
Section titled “The problem”Given a string, return the length of its longest substring (contiguous, not a subsequence) in which every character is distinct.
s = "abcabcbb" -> 3 ("abc")Key insight
Section titled “Key insight”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 bestexport function lengthOfLongestSubstring(s: string): number { const lastSeen = new Map<string, number>(); // char -> index of its latest occurrence let left = 0; let best = 0; for (let right = 0; right < s.length; right++) { const prev = lastSeen.get(s[right]); if (prev !== undefined && prev >= left) left = prev + 1; // jump just past the duplicate lastSeen.set(s[right], right); best = Math.max(best, right - left + 1); } return best;}import java.util.HashMap;import java.util.Map;
class Solution { public int lengthOfLongestSubstring(String s) { Map<Character, Integer> lastSeen = new HashMap<>(); // char -> index of its latest occurrence int left = 0, best = 0; for (int right = 0; right < s.length(); right++) { char ch = s.charAt(right); Integer prev = lastSeen.get(ch); if (prev != null && prev >= left) left = prev + 1; // jump just past the duplicate lastSeen.put(ch, right); best = Math.max(best, right - left + 1); } return best; }}Complexity
Section titled “Complexity”- Time: O(n) —
rightvisits each character once, andleftonly moves forward. - Space: O(k) — the map holds at most one entry per distinct character, where
kis the alphabet size (at mostn).
Watch out for
Section titled “Watch out for”- Only react to duplicates inside the window. In
"abba", when the finalaarrives its old index 0 is already left ofleft. Without the>= leftcheck,leftjumps 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
beststays 0. No special case needed.
Variations
Section titled “Variations”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.
Permutation in String (LeetCode 567)
Section titled “Permutation in String (LeetCode 567)”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.
Minimum Size Subarray Sum (LeetCode 209)
Section titled “Minimum Size Subarray Sum (LeetCode 209)”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.