#3696
Easy Algorithms Maximum distance between unequal words in array i
Array String
83.2% acceptance
Mar 31, 2026
6
0
You are given a string array words.
Find the maximum distance between two distinct indices i and j such that:
words[i] != words[j], and
the distance is defined as j - i + 1.
Return the maximum distance among all such pairs. If no valid pair exists, return 0.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_distance(words: Vec<String>) -> i32 {
let n = words.len();
let mut ans = 0i32;
// Best uses either smallest i or largest j
// Try i=0 with largest j where words[0] != words[j]
for j in (1..n).rev() {
if words[0] != words[j] {
ans = ans.max((j + 1) as i32);
break;
}
}
// Try j=n-1 with smallest i where words[i] != words[n-1]
for i in 0..n - 1 {
if words[i] != words[n - 1] {
ans = ans.max((n - i) as i32);
break;
}
}
ans
}
}