Maximum Number of Matching Indices After Right Shifts - Problem
You're given two integer arrays nums1 and nums2 of equal length. Your mission is to find the maximum number of indices where elements match after performing any number of right shifts on nums1.
An index i is considered matching when nums1[i] == nums2[i]. A right shift moves every element one position to the right, with the last element wrapping around to the first position.
Example: Array [1,2,3,4] becomes [4,1,2,3] after one right shift.
Your goal is to determine the optimal number of right shifts that maximizes the count of matching indices between the two arrays.
Input & Output
example_1.py โ Basic Rotation
$
Input:
nums1 = [1,2,3,4], nums2 = [2,3,4,1]
โบ
Output:
4
๐ก Note:
After 1 right shift, nums1 becomes [4,1,2,3]. After 2 right shifts, nums1 becomes [3,4,1,2]. After 3 right shifts, nums1 becomes [2,3,4,1], which perfectly matches nums2, giving us 4 matching indices.
example_2.py โ Partial Match
$
Input:
nums1 = [1,2,3], nums2 = [3,1,2]
โบ
Output:
3
๐ก Note:
After 2 right shifts, nums1 becomes [2,3,1]. After 1 right shift, nums1 becomes [3,1,2], which exactly matches nums2 at all positions.
example_3.py โ No Perfect Match
$
Input:
nums1 = [1,1,1], nums2 = [1,2,3]
โบ
Output:
1
๐ก Note:
No matter how we rotate nums1 (all elements are 1), we can only match one position with nums2 at index 0. The maximum number of matches is 1.
Constraints
- 1 โค nums1.length == nums2.length โค 1000
- 1 โค nums1[i], nums2[i] โค 109
- Both arrays have the same length
Visualization
Tap to expand
Understanding the Visualization
1
Initial Position
Both arrays start in their original positions
2
Try Rotations
Rotate nums1 by 0, 1, 2... n-1 positions
3
Count Matches
For each rotation, count how many positions have equal values
4
Find Maximum
Return the highest match count found across all rotations
Key Takeaway
๐ฏ Key Insight: Since there are only n possible rotations, we can afford to test them all. The mathematical approach using `(i - shift + n) % n` elegantly simulates rotations without array manipulation.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code