Video in progress
Find the length of the longest substring without repeating characters.
With a variable window: I advance the right edge and keep each character's last seen index in a map. If a repeated character is inside the window, I jump the left edge to the position right after it. O(n).
📖 Answer
"abcabcbb" → "abc", answer 3. "pwwkew" → "wke", answer 3.
static int longestUnique(String s) {
Map<Character, Integer> last = new HashMap<>();
int left = 0, best = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
Integer prev = last.get(c);
if (prev != null && prev >= left) {
left = prev + 1;
}
last.put(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}
The place where people make the most mistakes is the prev >= left condition. Walk through "abba" by hand: when the second a arrives, its previous index is 0, but left is already at 2. If you write it without the condition, left moves backward and the answer comes out wrong.
Each character enters the window once and the left edge only moves forward, so it's O(n). If it's only ASCII, an int[128] instead of the map runs faster.
Sign up to mark studied questions and save your progress.