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
- 0 ≤ s.length ≤ 5 · 10⁴
- s may contain letters, digits, symbols and spaces
Edge cases to test
- Empty string:
0 - All the same character:
1 - A repeat far back:
"abba"(left must not move backwards)
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 bestC++
#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
- Best Time to Buy and Sell Stock (Easy)
- Minimum Size Subarray Sum (Medium)
- Maximum Sum Subarray of Size K (Easy)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)
- Subarrays with K Different Integers (Hard)