[LeetCode] Minimum Swaps to Move Zeros to End

3936. Minimum Swaps to Move Zeros to End

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.

1
2
3
4
5
6
7
8
class Solution {
public:
int minimumSwaps(vector<int>& nums) {
int zero = count(begin(nums), end(nums), 0), res = 0;
for(int i = nums.size() - zero - 1; i >= 0; i--) if(!nums[i]) res++;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-swaps-to-move-zeros-to-end/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.