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
Maximum Matching Indices VisualizationStep 1: Original Arrays1234nums1:2341nums2:Step 2: Test Rotation 32341rotated:2341nums2:Perfect Match! All 4 indices matchRotationAlgorithm: Test all rotations (0 to n-1) and find maximum matchesTime: O(nยฒ) | Space: O(1)
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.
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 15
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen