Longest Substring Without Repeating Characters

Pattern: Sliding window: variable size

medium

Grow the window one character at a time. When the new character already appears in the window, jump the left edge just past its last copy.

The problem

Given a string, return the length of the longest block of neighbouring characters in which no character appears twice. For example, "abcabcbb" gives 3 ("abc"), "bbbbb" gives 1, and "pwwkew" gives 3 ("wke"). Note that "pwke" does not count, because it is not a block of neighbours. The empty string gives 0.

The function name lengthOfLongestSubstring matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • If the block from left to right has no repeats and the next character is new, what is the next block?
  • If the next character is already in the block, which starts are now impossible?
  • How can you know, in O(1), where a character last appeared?

Hints

    Brute force, and why it fails

    Check every block for repeats: O(n²) blocks, each checked with a set. The window looks at each character once: O(n).

    The key insight

    The best block ending at right starts just after the last repeat of any character in it. Tracking last positions lets left jump there directly, and left never moves back.

    Dry run

    p0left
    w1 
    w2 
    k3 
    e4 
    w5 
    best0

    s = pwwkew. last remembers where each character was last seen. The window starts empty with left = 0.

    Step 1 of 5

    The plan

    last = empty map, left = 0, best = 0
    for right from 0 to n - 1:
        c = s[right]
        if c in last and last[c] >= left:
            left = last[c] + 1
        last[c] = right
        best = max(best, right - left + 1)
    return best
    

    Complexity

    Time
    O(n)
    Space
    O(min(n, alphabet))

    One pass. The map holds at most one entry per distinct character, which is at most 128 for ASCII text.

    Edge cases

    • Empty string: 0.
    • A single space, " ": 1. Spaces are characters too.
    • "abba": when the second a arrives, its old copy (index 0) is before left (2), so left must not move back. The answer is 2.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] last = new int[128];              // last index where each character was seen
            Arrays.fill(last, -1);
            int left = 0, best = 0;
            for (int right = 0; right < s.length(); right++) {
                char c = s.charAt(right);
                if (last[c] >= left) {
                    left = last[c] + 1;             // c repeats inside the window: jump past its old copy
                }
                last[c] = right;
                best = Math.max(best, right - left + 1);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            vector<int> last(128, -1);              // last index where each character was seen
            int left = 0, best = 0;
            for (int right = 0; right < static_cast<int>(s.size()); right++) {
                unsigned char c = s[right];
                if (last[c] >= left) {
                    left = last[c] + 1;             // c repeats inside the window: jump past its old copy
                }
                last[c] = right;
                best = max(best, right - left + 1);
            }
            return best;
        }
    };

    Python

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            last = {}                               # last index where each character was seen
            left = best = 0
            for right, c in enumerate(s):
                if last.get(c, -1) >= left:
                    left = last[c] + 1              # c repeats inside the window: jump past its old copy
                last[c] = right
                best = max(best, right - left + 1)
            return best

    Common mistakes

    • Setting left = last[c] + 1 without checking last[c] >= left, which moves left backwards on inputs like "abba".
    • Clearing the whole set when a repeat appears, which throws away a valid part of the window.
    • Returning the substring instead of its length.

    Similar problems