Find the Minimum Cost Array Permutation - Problem

You are given an array nums which is a permutation of [0, 1, 2, ..., n - 1].

The score of any permutation of [0, 1, 2, ..., n - 1] named perm is defined as:

score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|

Return the permutation perm which has the minimum possible score. If multiple permutations exist with this score, return the one that is lexicographically smallest among them.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1, 0, 2]
Output: [0, 1, 2]
💡 Note: For permutation [0,1,2]: score = |0-nums[1]| + |1-nums[2]| + |2-nums[0]| = |0-0| + |1-2| + |2-1| = 0 + 1 + 1 = 2. This is the minimum possible score.
Example 2 — Minimum Size
$ Input: nums = [0]
Output: [0]
💡 Note: Only one element, so the only permutation is [0]. Score = |0-nums[0]| = |0-0| = 0.
Example 3 — Larger Array
$ Input: nums = [1, 3, 0, 2]
Output: [0, 2, 3, 1]
💡 Note: Optimal permutation gives score = |0-nums[2]| + |2-nums[3]| + |3-nums[1]| + |1-nums[0]| = |0-0| + |2-2| + |3-3| + |1-1| = 0. This is lexicographically smallest among optimal solutions.

Constraints

  • 1 ≤ nums.length ≤ 14
  • nums is a permutation of [0, 1, 2, ..., n - 1]

Visualization

Tap to expand
Find Minimum Cost Array PermutationInput: nums = [1, 0, 2]102idx 0idx 1idx 2Try permutation [0, 1, 2]:Cost = |0 - nums[1]| + |1 - nums[2]| + |2 - nums[0]| = |0 - 0| + |1 - 2| + |2 - 1| = 0 + 1 + 1 = 2012perm[0]perm[1]perm[2]Circular arrangementOutput: [0, 1, 2] with minimum cost = 2
Understanding the Visualization
1
Input
Array nums = [1, 0, 2] representing values at positions
2
Process
Find permutation perm where circular sum |perm[i] - nums[perm[(i+1)%n]]| is minimized
3
Output
Return lexicographically smallest optimal permutation [0, 1, 2]
Key Takeaway
🎯 Key Insight: Model as circular TSP using bitmask DP to efficiently explore all permutations while maintaining lexicographic order
Asked in
Google 8 Amazon 5
6.8K Views
Medium Frequency
~35 min Avg. Time
180 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen