KatInterview

Rotation Distance: Sum Absolute Differences Across All Shifts

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingarraysrotationsorting

Last updated

Tests array rotation mechanics, computing position-wise absolute differences for every cyclic offset, and returning results in sorted order.

You are given two integer arrays first and second, both of length n. Your task is to compute a distance score for every possible cyclic rotation of first when compared against second, then return all scores in ascending order.

For a rotation amount k (where 0 ≤ k < n), the rotated version of first places the element originally at index i into position (i - k) mod n. Equivalently, position i in the rotated array holds first[(i + k) mod n] from the original.

The distance score for rotation k is calculated as:

  • Sum |first[(i + k) mod n] - second[i]| across all indices i from 0 to n - 1.

Compute this score for every rotation amount from 0 through n - 1, then return the list of all n scores sorted in non-descending order. If multiple rotations yield the same score, include all duplicates in the output.

Constraints

  • 1 ≤ n ≤ 1000
  • len(first) == len(second) == n
  • 0 ≤ first[i], second[i] ≤ 10⁶
  • Each distance score fits within a 32-bit signed integer

Examples

Example 1

Input: rotation_distance_scores([1, 2, 3], [3, 1, 2])

Output: [0, 4, 4]

Example 2

Input: rotation_distance_scores([4, 0, 6, 1], [2, 5, 1, 3])

Output: [4, 6, 14, 14]

Example 3

Input: rotation_distance_scores([5], [2])

Output: [3]

Hints

Hint 1

Instead of calculating modular indices repeatedly, concatenate the first array with itself to make rotation slicing straightforward.

Hint 2

With n ≤ 1000, computing all n rotation scores at O(n) each results in O(n²) total work, which is efficient enough.

Hint 3

Remember to keep duplicate scores in your output—the result must always contain exactly n values after sorting.