Ctrl K

Cheapest Ring Order

Hard
You are given links, a permutation of 0, 1, …, n - 1. An order order is also a permutation of those numbers, laid out in a ring: the first element follows the last. Its cost is |order[0] - links[order[1]]| + |order[1] - links[order[2]]| + … + |order[n - 1] - links[order[0]]|. Return an order of minimum cost. If several exist, return the lexicographically smallest one.
Example 1
links=[2, 0, 1] → [0, 1, 2]

For the order [0, 1, 2]: |0 - links[1]| + |1 - links[2]| + |2 - links[0]| = 0 + 0 + 0 = 0, which cannot be beaten.

Example 2
links=[1, 0, 3, 2] → [0, 1, 3, 2]

The order [0, 1, 3, 2] costs 0 + 1 + 0 + 1 = 2. Other orders also cost 2, but this one is lexicographically smallest.

Constraints
  • 2 ≤ n = len(links) ≤ 14
  • links is a permutation of 0 to n - 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSettle Up in the Fewest Transfers HardTwo Groups With the Same Average HardAssembling Fragments HardSquare-Sum Chains HardSmallest Team With Every Skill Hard
loading Python…
Input
links=[2, 0, 1]
Expected
[0, 1, 2]

Run checks the first 3 tests in your browser. Submit checks all 92 tests on the server, hidden ones included.