#3090
Easy Algorithms Maximum length substring with two occurrences
Hash Table String Sliding Window
65.2% acceptance
Feb 25, 2026
253
21
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn maximum_length_substring(s: String) -> i32 {
let b = s.as_bytes();
let n = b.len();
let mut freq = [0u8; 26];
let mut l = 0;
let mut ans = 0;
for r in 0..n {
freq[(b[r] - b'a') as usize] += 1;
while freq[(b[r] - b'a') as usize] > 2 {
freq[(b[l] - b'a') as usize] -= 1;
l += 1;
}
ans = ans.max(r - l + 1);
}
ans as i32
}
}