Rotation Distance: Sum Absolute Differences Across All Shifts
Arrays & HashingAuto-graded · 23 test casesLast 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 indicesifrom0ton - 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 ≤ 1000len(first) == len(second) == n0 ≤ 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is computing a distance metric between second and every cyclic rotation of first, then organizing the results in sorted order.
Key insight: Rather than managing modular arithmetic (i + k) % n inside nested loops, concatenate first with itself to create a doubled array. The rotation by k positions is then simply the contiguous slice doubled[k:k + n], which naturally wraps around because doubled[k + i] equals first[(k + i) % n] for all valid indices.
Algorithm steps:
- Build
doubled = first + firstso that any rotation is a contiguous window of lengthn. - For each rotation offset
kfrom0ton - 1:- Extract the slice
doubled[k:k + n]representing the rotated array. - Pair each element of this slice with the corresponding element in
second. - Sum the absolute differences to get the distance score for rotation
k.
- Extract the slice
- Collect all
nscores into a list (preserving duplicates). - Sort the list in ascending order and return it.
Why this works:
- The doubling trick eliminates boundary conditions and makes rotations explicit as slices.
- Each rotation is evaluated independently, ensuring every offset from
0ton - 1contributes exactly one score. - Sorting produces the required non-descending output, and since we use a list rather than a set, duplicate scores are retained.
Complexity:
- Time: O(n²) to compute
nrotations at O(n) each, plus O(n log n) for sorting. The quadratic term dominates, yielding roughly 10⁶ operations at the maximum constraint ofn = 1000, which is efficient. - Space: O(n) for the doubled array and the output list.
Edge cases:
- Single-element arrays (
n = 1): only one rotation exists; output is a one-element list. - All rotations yield identical scores: the output will be
ncopies of the same value. - When
firstis already a rotation ofsecond, at least one rotation will produce a score of zero.
from typing import List
def rotation_distance_scores(first: List[int], second: List[int]) -> List[int]:
n = len(first)
doubled = first + first
scores = []
for k in range(n):
rotated = doubled[k:k + n]
scores.append(sum(abs(a - b) for a, b in zip(rotated, second)))
scores.sort()
return scores