LeetCode #159 - Longest Substring with At Most Two Distinct Characters
Given a string s, return the length of the longest substring that contains at most two distinct characters. This problem requires an understanding of the sliding window technique to efficiently find the maximum length of the substring under the specified constraint. Function Signature:def length_of_longest_substring_two_distinct(s: str) -> int: Example 1: Input: s = "eceba" Output: 3 Explanation: The substring is "ece" which contains two distinct characters. Example 2: Input: s = "aa" Output: 2 Explanation: The substring is "aa" which contains one distinct character. Constraints:
1 <= s.length <= 10^5
s consists of English letters, digits, symbols, and spaces.
Structured Response
#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
using namespace std;
int lengthOfLongestSubstringTwoDistinct(string s) {
int left = 0, right = 0, maxLength = 0;
unordered_map<char, int> charCount;
while (right < s.length()) {
charCount[s[right]]++;
while (charCount.size() > 2) {
charCount[s[left]]--;
if (charCount[s[left]] == 0) {
charCount.erase(s[left]);
}
left++;
}
maxLength = max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
int main() {
string s = "eceba";
cout << lengthOfLongestSubstringTwoDistinct(s) << endl;
return 0;
}
package main
import (
"fmt"
)
func lengthOfLongestSubstringTwoDistinct(s string) int {
left, right := 0, 0
charCount := make(map[rune]int)
maxLength := 0
for right < len(s) {
charCount[rune(s[right])]++
for len(charCount) > 2 {
charCount[rune(s[left])]--
if charCount[rune(s[left])] == 0 {
delete(charCount, rune(s[left]))
}
left++
}
if right-left+1 > maxLength {
maxLength = right - left + 1
}
right++
}
return maxLength
}
func main() {
s := "eceba"
fmt.Println(lengthOfLongestSubstringTwoDistinct(s))
}
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int lengthOfLongestSubstringTwoDistinct(String s) {
int left = 0, right = 0, maxLength = 0;
Map<Character, Integer> charCount = new HashMap<>();
while (right < s.length()) {
charCount.put(s.charAt(right), charCount.getOrDefault(s.charAt(right), 0) + 1);
while (charCount.size() > 2) {
charCount.put(s.charAt(left), charCount.get(s.charAt(left)) - 1);
if (charCount.get(s.charAt(left)) == 0) {
charCount.remove(s.charAt(left));
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
public static void main(String[] args) {
String s = "eceba";
System.out.println(lengthOfLongestSubstringTwoDistinct(s));
}
}
function lengthOfLongestSubstringTwoDistinct(s) {
let left = 0;
let right = 0;
const charCount = {};
let maxLength = 0;
while (right < s.length) {
charCount[s[right]] = (charCount[s[right]] || 0) + 1;
while (Object.keys(charCount).length > 2) {
charCount[s[left]]--;
if (charCount[s[left]] === 0) {
delete charCount[s[left]];
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
right++;
}
return maxLength;
}
// Example usage:
const s = "eceba";
console.log(lengthOfLongestSubstringTwoDistinct(s));
def length_of_longest_substring_two_distinct(s):
left, right = 0, 0
char_count = {}
max_length = 0
while right < len(s):
char_count[s[right]] = char_count.get(s[right], 0) + 1
while len(char_count) > 2:
char_count[s[left]] -= 1
if char_count[s[left]] == 0:
del char_count[s[left]]
left += 1
max_length = max(max_length, right - left + 1)
right += 1
return max_length
# Example usage:
s = "eceba"
print(length_of_longest_substring_two_distinct(s))
## Approach
Utilize a sliding window approach with two pointers to track the start and end of the substring. Maintain a hashmap to count character frequencies. When the count of distinct characters exceeds two, adjust the left pointer accordingly.
## Complexity
**Time:** O(n)
**Space:** O(1)
Share
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals 50+ Company Question Banks 5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.