Minimum Swaps to Move Zeros to End Problem
Description
LeetCode Problem 3936.
You are given an integer array nums.
In one operation, you can choose any two distinct indices i and j and swap nums[i] and nums[j].
Return an integer denoting the minimum number of operations required to move all 0s to the end of the array.
Example 1:
Input: nums = [0,1,0,3,12]
Output: 2
Explanation:
We perform the following swap operations:
- Swap nums[0] and nums[3], giving nums = [3, 1, 0, 0, 12].
- Swap nums[2] and nums[4], giving nums = [3, 1, 12, 0, 0].
Thus, the answer is 2.
Example 2:
Input: nums = [0,1,0,2]
Output: 1
Explanation:
We perform the following swap operations:
- Swap nums[0] and nums[3], giving nums = [2, 1, 0, 0].
Thus, the answer is 1.
Example 3:
Input: nums = [1,2,0]
Output: 0
Explanation:
The array already satisfies the condition. Therefore, no swap operations are needed.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 100
Solution
Approach: Two Pointers
Every swap can fix one zero that sits too far left by exchanging it with a non-zero that sits too far right. So we pair the leftmost misplaced zero with the rightmost misplaced non-zero.
Keep two pointers, i at the start and j at the end. Move i right until it points at a zero, and move j left until it points at a non-zero. If i < j, that pair needs one swap: count it and move both pointers inward. Stop when the pointers meet.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minimumSwaps(self, nums: List[int]) -> int:
ans = 0
n = len(nums)
i, j = 0, n - 1
while i < j:
while i < n and nums[i] != 0:
i += 1
while j and nums[j] == 0:
j -= 1
if i >= j:
break
ans += 1
i += 1
j -= 1
return ans