Sort Array by Moving Items to Empty Space Problem
Description
LeetCode Problem 2459.
You are given an integer array nums of size n containing each element from 0 to n - 1 (inclusive). Each of the elements from 1 to n - 1 represents an item, and the element 0 represents an empty space.
In one operation, you can move any item to the empty space. nums is considered to be sorted if the numbers of all the items are in ascending order and the empty space is either at the beginning or at the end of the array.
For example, if n = 4, nums is sorted if:
nums = [0,1,2,3]ornums = [1,2,3,0]
...and considered to be unsorted otherwise.
Return the minimum number of operations needed to sort nums.
Example 1:
Input: nums = [4,2,0,3,1]
Output: 3
Explanation:
- Move item 2 to the empty space. Now, nums = [4,0,2,3,1].
- Move item 1 to the empty space. Now, nums = [4,1,2,3,0].
- Move item 4 to the empty space. Now, nums = [0,1,2,3,4].
It can be proven that 3 is the minimum number of operations needed.
Example 2:
Input: nums = [1,2,3,4,0]
Output: 0
Explanation: nums is already sorted so return 0.
Example 3:
Input: nums = [1,0,2,4,3]
Output: 2
Explanation:
- Move item 2 to the empty space. Now, nums = [1,2,0,4,3].
- Move item 3 to the empty space. Now, nums = [1,2,3,4,0].
It can be proven that 2 is the minimum number of operations needed.
Constraints:
n == nums.length2 <= n <= 10^50 <= nums[i] < n- All the values of
numsare unique.
Solution
Approach: Permutation Cycles
Moving an item into the empty space is a swap with 0. Look at the cycles of the permutation: a cycle of length m that contains 0 needs m - 1 swaps, and a cycle of length m that does not contain 0 needs m + 1 swaps (one extra to bring 0 in and one to take it out).
Count m + 1 for every cycle of length at least 2, then subtract 2 if 0 is not already in its place, because its cycle only needs m - 1.
The empty space can end up at position 0 or at position n - 1, so compute the answer for both targets (the second by shifting every value by one) and take the minimum.
Complexity: O(n) time and O(n) space, where n is the length of the array.
class Solution:
def sortArray(self, nums: List[int]) -> int:
def f(nums, k):
vis = [False] * n
cnt = 0
for i, v in enumerate(nums):
if i == v or vis[i]:
continue
cnt += 1
j = i
while not vis[j]:
vis[j] = True
cnt += 1
j = nums[j]
return cnt - 2 * (nums[k] != k)
n = len(nums)
a = f(nums, 0)
b = f([(v - 1 + n) % n for v in nums], n - 1)
return min(a, b)