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
Minimum Cost Array Permutation INPUT nums array: 1 idx 0 0 idx 1 2 idx 2 Permutation space: [0,1,2], [0,2,1] [1,0,2], [1,2,0] [2,0,1], [2,1,0] Score Formula: |perm[i] - nums[perm[i+1]]| summed cyclically Input: nums = [1, 0, 2] ALGORITHM (DP) 1 State Definition dp[mask][last] = min cost using elements in mask 2 Fix First Element Start with perm[0]=0 (lexicographic smallest) 3 Transition Try adding each unused element, update cost 4 Backtrack Reconstruct optimal permutation path Score Calculation: perm=[0,1,2]: |0-nums[1]|+|1-nums[2]|+|2-nums[0]| = |0-0| + |1-2| + |2-1| = 2 Minimum Score! FINAL RESULT Optimal Permutation: 0 1 2 Cyclic Score Path: 0 1 2 Total Score: 2 |0-0|=0 |1-2|=1 |2-1|=1 [0, 1, 2] Key Insight: Use bitmask DP to track used elements. Since any cyclic rotation gives same score, fix perm[0]=0 to ensure lexicographically smallest result. Time: O(n^2 * 2^n) TutorialsPoint - Find the Minimum Cost Array Permutation | DP Approach
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