Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Example 1:
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2:
Input: nums = [0] Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
The problem requires moving all zeroes in an integer array to the end while maintaining the relative order of non-zero elements. This must be done in-place, meaning without creating a new array.
The most efficient solution uses the two-pointer approach. We maintain two pointers:
k
(or slow
in some implementations): This pointer keeps track of the index where the next non-zero element should be placed. It starts at 0.i
(or fast
in some implementations): This pointer iterates through the array.The algorithm iterates through the array. If nums[i]
is non-zero, it's swapped with nums[k]
, and k
is incremented. This effectively moves all non-zero elements to the beginning of the array, leaving zeroes in their original positions. After the iteration, the elements from index k
onwards will be all zeros.
The core logic remains the same across all languages, but syntax varies. Below are detailed explanations for a few examples:
Python:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
k = 0
for i, x in enumerate(nums):
if x: # If x is not 0 (truthy value)
nums[k], nums[i] = nums[i], nums[k] #Swap elements
k += 1
enumerate(nums)
efficiently provides both the index (i
) and value (x
) of each element.if x:
concisely checks if the element is non-zero.nums[k], nums[i] = nums[i], nums[k]
) performs the swap efficiently.Java:
class Solution {
public void moveZeroes(int[] nums) {
int k = 0;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] != 0) {
int temp = nums[i]; // Use a temporary variable for swapping
nums[i] = nums[k];
nums[k++] = temp;
}
}
}
}
temp
variable for swapping because simultaneous assignment isn't supported as directly as in Python.k++
post-increments k
after the swap.C++:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k = 0;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i]) {
swap(nums[i], nums[k++]); // Efficient swap using std::swap
}
}
}
};
std::swap
for efficient swapping.nums.size()
gets the array size.This two-pointer approach provides an optimal solution to the "Move Zeroes" problem, achieving linear time complexity and constant space complexity. The provided code examples demonstrate how this algorithm is implemented in various programming languages.