#1624
Easy Algorithms Largest substring between two equal characters
Hash Table String
68.3% acceptance
Feb 25, 2026
1407
68
Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
A substring is a contiguous sequence of characters within a string.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_length_between_equal_characters(s: String) -> i32 {
let s: Vec<u8> = s.bytes().collect();
let mut first = [usize::MAX; 26];
let mut ans = -1i32;
for (i, &c) in s.iter().enumerate() {
let idx = (c - b'a') as usize;
if first[idx] == usize::MAX {
first[idx] = i;
} else {
ans = ans.max(i as i32 - first[idx] as i32 - 1);
}
}
ans
}
}