Move Zeroes
EasyArrays · Two pointersO(n) time · O(1) space
The problem
Move all zeroes to the end of the array while keeping the relative order of the non-zero elements. Do it in place.
[0, 1, 0, 3, 12] → [1, 3, 12, 0, 0]Stuck? Open one hint
One pointer for where you are reading, one for where the next non-zero belongs.
Show the worked solution
Keep an insertAt pointer for the position the next non-zero element should occupy. Scan the array; every time you find a non-zero, write it at insertAt and advance.
After the scan, everything from insertAt to the end is zeroes — fill it. One pass, no extra array, order preserved.
Swapping instead of writing-then-filling also works and avoids the second loop. Either is fine; "in place and stable" is what is being checked.
KotlinO(n) time · O(1) space
fun moveZeroes(nums: IntArray) {
var insertAt = 0
for (n in nums) if (n != 0) nums[insertAt++] = n
while (insertAt < nums.size) nums[insertAt++] = 0
}