Maximum Number of Matching Indices After Right Shifts - Problem

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.

Input & Output

Example 1 — Perfect Match After One Shift
$ Input: nums1 = [1,2,3], nums2 = [3,1,2]
Output: 3
💡 Note: After 1 right shift, nums1 becomes [3,1,2] which perfectly matches nums2, giving us 3 matching indices.
Example 2 — Partial Matches
$ Input: nums1 = [1,2,3,4], nums2 = [4,3,2,1]
Output: 2
💡 Note: After 3 right shifts, nums1 becomes [2,3,4,1]. This matches nums2 at indices 1 and 2, giving us 2 matches.
Example 3 — No Improvement
$ Input: nums1 = [1,1,1], nums2 = [2,2,2]
Output: 0
💡 Note: No elements match regardless of rotation since all elements in nums1 are 1 and all in nums2 are 2.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 100
  • nums1.length == nums2.length
  • 1 ≤ nums1[i], nums2[i] ≤ 100

Visualization

Tap to expand
Maximum Matching Indices After Right Shifts INPUT nums1 (original) 1 2 3 i=0 i=1 i=2 nums2 (target) 3 1 2 Right Shift Operation: i --> (i + 1) % n After 1 right shift: [1,2,3] --> [3,1,2] Matches nums2! ALGORITHM STEPS 1 Iterate all shifts Try shift = 0 to n-1 2 Count matches For each shift amount 3 Compare indices nums1[(i+s)%n] == nums2[i] 4 Track maximum Update best count Shift Analysis Shift Result Matches 0 [1,2,3] 0 1 [3,1,2] 3 2 [2,3,1] 0 Max found at shift=1 FINAL RESULT After 1 Right Shift: nums1 shifted: 3 1 2 OK OK OK nums2: 3 1 2 Output: 3 All 3 indices match! Perfect alignment achieved with single right shift Key Insight: A right shift by k positions means element at index i moves to (i+k) % n. To find matches, we check if nums1[(i+shift) % n] equals nums2[i] for all shifts 0 to n-1. The optimized approach tests each shift in O(n) time, giving O(n^2) total. Best shift gives max matches. TutorialsPoint - Maximum Number of Matching Indices After Right Shifts | Optimized Single Pass
Asked in
Microsoft 15 Amazon 12 Google 8
25.5K Views
Medium Frequency
~15 min Avg. Time
850 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