Maximum Distance Between Unequal Words in Array II Problem
#3706
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3706.
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.
Example 1:
Input: words = ["leetcode","leetcode","codeforces"]
Output: 3
Explanation:
In this example, words[0] and words[2] are not equal, and they have the maximum distance 2 - 0 + 1 = 3.
Example 2:
Input: words = ["a","b","c","a","a"]
Output: 4
Explanation:
In this example words[1] and words[4] have the largest distance of 4 - 1 + 1 = 4.
Example 3:
Input: words = ["z","z","z"]
Output: 0
Explanation:
In this example all the words are equal, thus the answer is 0.
Constraints:
1 <= words.length <= 10^51 <= words[i].length <= 10words[i]consists of lowercase English letters.
Solution
Approach: Single Pass
One word of the best pair is always at an end of the array. Suppose the best pair were i < j with 0 < i < j < n - 1. Then words[0] must equal words[j] and words[n - 1] must equal words[i], otherwise a longer pair would exist. That makes words[0] and words[n - 1] different, and their distance n beats j - i + 1, a contradiction.
So for every index i, compare it with the first word (distance i + 1) and the last word (distance n - i) and keep the maximum.
Complexity: O(n) time and O(1) space.
class Solution:
def maxDistance(self, words: List[str]) -> int:
n = len(words)
ans = 0
for i in range(n):
if words[i] != words[0]:
ans = max(ans, i + 1)
if words[i] != words[-1]:
ans = max(ans, n - i)
return ans