Magicsheet logo

Find the Minimum Cost Array Permutation

Hard
12.5%
Updated 8/1/2025

Find the Minimum Cost Array Permutation

What is this problem about?

The Find the Minimum Cost Array Permutation interview question asks you to find a permutation PP of the integers [0,n1][0, n-1] such that a specific cost function is minimized. The cost is usually defined as the sum of P[i]nums[P[i+1]]|P[i] - nums[P[i+1]]| for all ii, wrapping around the array. You also need to return the lexicographically smallest permutation that achieves this minimum cost. Note that P[0]P[0] can always be fixed to 0 to simplify the search.

Why is this asked in interviews?

Google uses this "Hard" problem to test mastery of Dynamic Programming with Bitmasks and the Traveling Salesperson Problem (TSP) logic. The permutation is essentially a path through all numbers, and the cost depends on the transition between adjacent elements. It evaluations whether you can optimize a factorial O(N!)O(N!) search into an exponential O(2NimesN2)O(2^N imes N^2) one.

Algorithmic pattern used

This is a Bitmask Dynamic Programming problem.

  1. State: dp[mask][last_val] is the minimum cost to have visited the set of numbers in mask, with last_val being the most recent addition.
  2. Transition: For each number next_val not in the mask:
    • dp[mask | (1 << next_val)][next_val] = min(..., dp[mask][last_val] + cost(last_val, next_val)).
  3. Lexicographical Order: Since you need the smallest permutation, when transitions result in the same minimum cost, always pick the smaller next_val.
  4. Reconstruction: Use a parent or choice table to reconstruct the path from the DP table.

Example explanation

n=3,P[0]=0n=3, P[0]=0 fixed. Possible permutations: [0, 1, 2] and [0, 2, 1].

  1. Cost([0, 1, 2]) = 0nums[1]+1nums[2]+2nums[0]|0 - nums[1]| + |1 - nums[2]| + |2 - nums[0]|.
  2. Cost([0, 2, 1]) = 0nums[2]+2nums[1]+1nums[0]|0 - nums[2]| + |2 - nums[1]| + |1 - nums[0]|. The DP explores all 2n2^n subsets to find the minimum.

Common mistakes candidates make

  • Brute Force: Using O(N!)O(N!) which is only feasible for N10N \le 10.
  • Wrap-around: Forgetting to add the cost from the last element back to P[0]P[0].
  • Reconstruction error: Failing to correctly store the choices needed to build the permutation after the DP is complete.

Interview preparation tip

"Permutation of NN items" + "Cost depends on adjacent pairs" + "N20N \le 20" is the classic signature of Bitmask DP. Practice the TSP (Traveling Salesperson) problem as this is a direct variation of it.

Similar Questions