Maximum Number of Matching Indices After Right Shifts Problem
#3400
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 3400.
You are given two integer arrays, nums1 and nums2, of the same length.
An index i is considered matching if nums1[i] == nums2[i].
Return the maximum number of matching indices after performing any number of right shifts on nums1.
A right shift is defined as shifting the element at index i to index (i + 1) % n, for all indices.
Example 1:
Input: nums1 = [3,1,2,3,1,2], nums2 = [1,2,3,1,2,3]
Output: 6
Explanation:
If we right shift nums1 2 times, it becomes [1, 2, 3, 1, 2, 3]. Every index matches, so the output is 6.
Example 2:
Input: nums1 = [1,4,2,5,3,1], nums2 = [2,3,1,2,4,6]
Output: 3
Explanation:
If we right shift nums1 3 times, it becomes [5, 3, 1, 1, 4, 2]. Indices 1, 2, and 4 match, so the output is 3.
Constraints:
nums1.length == nums2.length1 <= nums1.length, nums2.length <= 30001 <= nums1[i], nums2[i] <= 10^9
Solution
Approach: Enumeration
Try every number of right shifts k from 0 to n - 1. For each one, count the indices where the shifted nums1 equals nums2, and keep the largest count. Comparing nums1[(i + k) % n] with nums2[i] for all k covers exactly the same set of rotations as shifting right.
Complexity: O(n^2) time, O(1) extra space.
class Solution:
def maximumMatchingIndices(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
ans = 0
for k in range(n):
t = sum(nums1[(i + k) % n] == x for i, x in enumerate(nums2))
ans = max(ans, t)
return ans