Problem Description
You are given an integer array nums of size n that contains every integer from 0 to n-1 (inclusive). In this array the number 0 represents an empty space and every other number (from 1 to n-1) represents an item. In one operation you may move any item to the empty space. The array is considered sorted if the items (numbers 1 through n-1) are in ascending order and the empty space (0) is either at the beginning or at the end of the array. Return the minimum number of operations required to sort the array.
Key Insights
- The only allowed operation is to move an item directly into the empty space, which “shifts” the empty space to the moved item’s location.
- There are two possible target configurations: one with 0 at the beginning (target1: [0,1,2,…,n–1]) and one with 0 at the end (target2: [1,2,…,n–1,0]). We can compute the minimum moves required for both and take the minimum.
- The transformation can be modeled as a permutation of indices. For each target configuration, define a mapping f on indices where for index i (with value v = nums[i]) the desired index is:
- For target1 (empty at beginning): if v == 0 then expected index is 0, otherwise expected index is v.
- For target2 (empty at end): if v == 0 then expected index is n–1, otherwise expected index is v–1.
- The permutation can be decomposed into disjoint cycles. For each cycle:
- If the cycle length is 1 (already in place), no move is needed.
- If the cycle contains the position that must hold the empty space in the target configuration then the cost is (cycle length – 1).
- Otherwise the cost is (cycle length + 1) because moving items into a cycle that does not contain the empty requires an extra move.
- The final answer is the minimum total cost among the two target configurations.
Space and Time Complexity
Time Complexity: O(n) — we iterate through the array and each index is visited exactly once during cycle decomposition. Space Complexity: O(n) — additional arrays (e.g. visited marker and mapping) use linear extra space.
Solution
We solve the problem by “simulating” the sorting process indirectly via cycle decomposition of a permutation. For any chosen target configuration (empty at beginning or at end), we first build a mapping from each index i (the current position) to its expected position based on the target order. Then, we perform a cycle decomposition on this permutation. For each cycle: • If it is of length 1 (already correct) we do nothing. • If the cycle includes the target index for the empty space then we can fix it in (length – 1) moves. • Otherwise, fixing the cycle requires an extra move (i.e. cost = cycle length + 1). The answer is the minimum total moves computed between the two possible target “sorted” orders.