FastPrepSorted Cyclic Shift Difference Sums

Sorted Cyclic Shift Difference Sums

Capital One logoCapital One● MediumFULLTIMEOA
Learn

Problem statement

Given two integer arrays nums1 and nums2 of equal length, consider every cyclic right shift of nums1. For shift s, the value aligned with index i is nums1[(i - s + n) % n].

For every shift, compute the sum of absolute differences between aligned values from the shifted nums1 and nums2. Return all n sums sorted in nondecreasing order.

Function

sortedCyclicShiftDifferences(nums1: int[], nums2: int[]) → long[]

Examples

Example 1

nums1 = [1,2,3]nums2 = [2,1,3]return = [2,2,4]

The right shifts are [1,2,3], [3,1,2], and [2,3,1], with difference sums 2, 2, and 4.

Example 2

nums1 = [5]nums2 = [-2]return = [7]

A one-element array has only one cyclic shift.

Example 3

nums1 = [0,10]nums2 = [10,0]return = [0,20]

The unshifted alignment costs 20, while shifting right once makes the arrays equal.

Constraints

  • 1 <= nums1.length = nums2.length <= 500.
  • -10^9 <= nums1[i], nums2[i] <= 10^9.
  • Use 64-bit arithmetic for every sum.

More Capital One problems

See Capital One hiring insights
public long[] sortedCyclicShiftDifferences(int[] nums1, int[] nums2) {
    // Write your code here.
}
nums1[1,2,3]
nums2[2,1,3]
expected[2,2,4]
Checking account…