Maximum Distance Between Unequal Words in Array I

You are given an array of strings words of length n.

Your task is to determine the maximum distance between two different positions i and j such that:

  • 0 ≤ i < j < n
  • words[i] and words[j] are not equal

The distance between index i and j is defined as: distance = j - i + 1

Return the maximum possible distance among all valid pairs.

If there is no pair of indices satisfying the condition, return 0.

Example 1:

Input: words = ["apple", "banana", "apple", "grape"]

Output: 4

Explanation:

  • The pair (0, 3) → "apple" and "grape" are different.
  • Distance = 3 - 0 + 1 = 4.
  • No other valid pair gives a larger distance.

Example 2:

Input: words = ["cat", "dog", "cat", "cat", "dog"]

Output: 5

Explanation:

  • The pair (0, 4) → "cat" and "dog" are different.
  • Distance = 4 - 0 + 1 = 5.
  • This is the maximum possible distance.

Now Your Turn!

Pick the correct output for the given input

Input: words = ["x", "y", "x", "y"]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ n = words.length ≤ 100
  • 1 ≤ words[i].length ≤ 20
  • words[i] consists only of lowercase English letters.
  • Indices are zero-based.
  • The solution must consider all valid pairs (i, j) where i < j.

Hints

Frequently Occurring Doubts

0
class Solution {
public:
int maxDistance(vector<string>& words) {
// Your code goes here
}
};
Test Case

Input:

Words