Skip to main content
Back to problems
#159
Medium Algorithms

Longest substring with at most two distinct characters

Hash Table String Sliding Window
57.0% acceptance
Mar 31, 2026
2271
40
Given a string s, return the length of the longest substring that contains at most two distinct characters.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn length_of_longest_substring_two_distinct(s: String) -> i32 {
    let bytes = s.as_bytes();
    let mut count = [0i32; 128];
    let mut distinct = 0;
    let mut left = 0;
    let mut ans = 0;
    for right in 0..bytes.len() {
      let c = bytes[right] as usize;
      if count[c] == 0 {
        distinct += 1;
      }
      count[c] += 1;
      while distinct > 2 {
        let lc = bytes[left] as usize;
        count[lc] -= 1;
        if count[lc] == 0 {
          distinct -= 1;
        }
        left += 1;
      }
      ans = ans.max(right - left + 1);
    }
    ans as i32
  }
}