Problem Description
Given two integer arrays nums1 and nums2 of equal length, determine the maximum number of indices where the two arrays have the same value after performing any number of right shifts on nums1. A right shift moves every element of nums1 one position to the right (with the last element wrapping around to the first position).
Key Insights
- A right shift on nums1 rotates the array, and we want to align as many elements as possible with nums2.
- For any index i in nums1, after k right shifts, the element moves to index (i + k) mod n.
- To get a match at an index j in nums2, for each element at index i in nums1, we want (i + k) mod n == j where nums1[i] == nums2[j]. This gives k = (j - i + n) mod n.
- Counting the frequency of each shift k that results in a match across the arrays allows us to choose the optimal shift.
Space and Time Complexity
Time Complexity: O(n * m) in the worst-case scenario where m is the average occurrences of a number in nums2. With n bounded by 3000, this approach is acceptable. Space Complexity: O(n) for the hash map storing indices of nums2 values and O(n) for counting frequencies.
Solution
The idea is to precompute a mapping from each value in nums2 to its indices. Then, iterate over nums1 and for each element, check all corresponding positions in nums2 where the same value occurs. For each such pair, calculate the required shift (k = (j - i + n) % n) that would align these two elements. Count the frequency for each k and finally return the maximum frequency. This provides the maximum number of matching indices after an optimal right shift.