Algo-Sim › Sliding Window

Longest Substring Without Repeating Characters

Medium · Sliding Window · step through it in Java, Python and C++ on your own input

Return the length of the longest substring whose characters are all different.

Problem

Given a string s, find the longest contiguous substring in which no character occurs twice, and return its length.

Constraints

Edge cases to test

Follow-up questions

How do you avoid shrinking one step at a time?
Store the last index of each character and jump left to max(left, last[c] + 1): each index is touched once.
What if at most k repeats are allowed?
Count characters in the window and shrink while any count exceeds k + 1, or track how many characters are over the limit.

Solution

Java

public int lengthOfLongestSubstring(String s) {
    Set<Character> window = new HashSet<>();
    int left = 0, best = 0;
    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);
        while (window.contains(c)) {
            window.remove(s.charAt(left));
            left++;
        }
        window.add(c);
        best = Math.max(best, right - left + 1);
    }
    return best;
}

Python

def length_of_longest_substring(s):
    window = set()
    left = best = 0
    for right in range(len(s)):
        c = s[right]
        while c in window:
            window.remove(s[left])
            left += 1
        window.add(c)
        best = max(best, right - left + 1)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int lengthOfLongestSubstring(string &s) {
        unordered_set<char> window = {};
        int left = 0, best = 0;
        for (int right = 0; right < int(s.size()); right++) {
            char c = s[right];
            while (window.count(c)) {
                window.erase(s[left]);
                left++;
            }
            window.insert(c);
            best = std::max(best, right - left + 1);
        }
        return best;
    }
};

More Sliding Window problems