Tech Interview RoomStudy guides

Sliding Window

Find the length of the longest substring without repeating characters.

Intermediate · 2 min read · Lesson 2 of 5 in Sliding Window

Problem

For "abcabcbb" the answer is 3 ("abc"); for "pwwkew" it is 3 ("wke").

Approach: sliding window

Maintain a window [left, right] with no duplicates. Store the last index of each character. When s[right] was last seen inside the window, jump left past that position. Each character is processed once.

java
import java.util.HashMap;
import java.util.Map;

class LongestUniqueSubstring {
    static int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> lastIndex = new HashMap<>();
        int best = 0;
        for (int left = 0, right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            Integer prev = lastIndex.get(c);
            if (prev != null && prev >= left) left = prev + 1;   // shrink past the duplicate
            lastIndex.put(c, right);
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb")); // 3
        System.out.println(lengthOfLongestSubstring("pwwkew"));   // 3
        System.out.println(lengthOfLongestSubstring("abba"));     // 2
    }
}

Complexity

O(n) time; O(min(n, alphabet)) space. For ASCII input an int[128] array instead of a map is faster.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why check `prev >= left`?

The map remembers characters that may already be outside the current window. In "abba", when the second a arrives, its previous index 0 is left of the window (which starts at 2 after the second b); jumping left back to 1 would wrongly re-include the duplicate b. Only move left forward.

How would you find the longest substring with at most K distinct characters?

Same sliding window with a frequency map: expand right, and while the map has more than K keys, decrement s[left]'s count (removing it at zero) and advance left. Track the maximum window length. O(n) time.