Sorted Sums of Absolute Differences Over All Cyclic Shifts of an Array
Capital OneSoftware Engineer · Online AssessmentLast updated
Given two integer arrays of equal length, compute the sum of absolute differences between the second array and every cyclic rotation of the first, then return all of these sums in non-descending order. It tests rotation index arithmetic, accumulation over every shift, and exact output ordering.
You are given two integer arrays nums1 and nums2 of the same length n. For each shift t from 0 to n - 1, rotate nums1 cyclically by t positions and add up the absolute differences between the rotated array and nums2, position by position. Return all n sums sorted in non-descending order.
Function Signature
def cyclic_shift_diff_sums(nums1: list[int], nums2: list[int]) -> list[int]:
Rules
- The shift-
trotation ofnums1is the array whose element at indexiisnums1[(i + t) % n]. - The sum for shift
tisS(t) = sum(abs(nums1[(i + t) % n] - nums2[i]) for i in range(n)). - Return
[S(0), S(1), ..., S(n - 1)]sorted in non-descending order. Keep duplicates: the result always has exactlynvalues. - Because every shift is included and the result is sorted, rotating in the other direction gives the same answer.
Constraints
1 <= n <= 1000len(nums1) == len(nums2) == n0 <= nums1[i], nums2[i] <= 10^6- Every sum is at most
n * 10^6 <= 10^9, which fits in a 32-bit signed integer.
Examples
Example 1
Input: nums1 = [1, 2, 3], nums2 = [3, 1, 2]
Output: [0, 4, 4]
Shift 0 pairs [1, 2, 3] with [3, 1, 2]: 2 + 1 + 1 = 4. Shift 1 pairs [2, 3, 1] with it: 1 + 2 + 1 = 4. Shift 2 pairs [3, 1, 2] with it: 0 + 0 + 0 = 0.
Example 2
Input: nums1 = [4, 0, 6, 1], nums2 = [2, 5, 1, 3]
Output: [4, 6, 14, 14]
The rotations are [4, 0, 6, 1], [0, 6, 1, 4], [6, 1, 4, 0] and [1, 4, 0, 6], giving sums 2 + 5 + 5 + 2 = 14, 2 + 1 + 0 + 1 = 4, 4 + 4 + 3 + 3 = 14 and 1 + 1 + 1 + 3 = 6.
Example 3
Input: nums1 = [5], nums2 = [2]
Output: [3]
The only shift pairs 5 with 2.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.