Skip to main content
Back to problems
#3706
Medium Algorithms

Maximum distance between unequal words in array ii

Array String
72.1% acceptance
Mar 31, 2026
5
2
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)
LeetCode
solution.rs
impl Solution {
  pub fn max_distance(words: Vec<String>) -> i32 {
    let n = words.len();
    if n < 2 {
      return 0;
    }
    let mut ans = 0i32;
    for j in (1..n).rev() {
      if words[j] != words[0] {
        ans = ans.max(j as i32 + 1);
        break;
      }
    }
    for i in 0..n - 1 {
      if words[i] != words[n - 1] {
        ans = ans.max((n - i) as i32);
        break;
      }
    }
    ans
  }
}