Move Zeroes
EasyGiven an integer array nums, move all 0's to the end while maintaining the relative order of the non-zero elements. Do this in-place without making a copy of the array.
Examples
| Input | Output |
|---|---|
| nums = [0,1,0,3,12] | [1,3,12,0,0] |
| nums = [0] | [0] |
Python Solution
def move_zeroes(nums: list[int]) -> None:
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1JavaScript Solution
function moveZeroes(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== 0) {
[nums[write], nums[read]] = [nums[read], nums[write]];
write++;
}
}
}Step-by-Step Explanation
- Two pointers: write is where the next non-zero goes.
- When we see a non-zero, swap with write position and increment write.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
ArrayTwo Pointers
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateIntersection of Two ArraysLongest Common Prefix