Move Zeroes
Solve and submit on LeetCode to build your LeetCode profile. Use the hints here when you need guidance.
Problem
Given an integer array, shift every zero to the end while keeping the non-zero values in their original relative order. The rearrangement must happen in place, without allocating a second array.
Examples
Constraints
- • 1 <= nums.length <= 10^4
- • -2^31 <= nums[i] <= 2^31 - 1
Hints & approach
Hint 1
Think about where the next non-zero value should be written.
Hint 2
Keep a write pointer that only advances when you place a non-zero value.
Hint 3
Swapping the current value with the write position moves zeros backward for free.
Approachtry the hints first
Maintain a pointer write that marks where the next non-zero element belongs. Scan the array with a read pointer; whenever the value is non-zero, swap it into write and advance write. Every zero that gets swapped lands in the region after write, so when the scan finishes all zeros sit at the end. Relative order of non-zero values is preserved because they are placed in the order they are read.
Time O(n) · Space O(1)
