↻one more pass.
Sliding window · Medium

Longest Substring Without Repeating Characters: the idea to remember.

Find the longest contiguous substring containing no repeated character.

Solve on LeetCode ↗

The core insight

Move the left boundary past the last occurrence of a repeated character, never backward.

Why it works

The window has no duplicates after moving left. A last occurrence before left must not change the current window.

The mistake to avoid

Use Math.max for the left boundary. In abba, a stale occurrence must not move left backward.

Time: O(n) expectedSpace: O(min(n, alphabet size))

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int lengthOfLongestSubstring(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);
        if (last.containsKey(c)) left = Math.max(left, last.get(c) + 1);
        last.put(c, right);
        best = Math.max(best, right - left + 1);
    }
    return best;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.