The problem. Given an integer array nums, move every 0 to the end while keeping the relative order of the non-zero elements. Do it in place, without returning a new array.
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Input: nums = [0]
Output: [0]Two rules make this more than a sort: the non-zero values must keep their original order (1, then 3, then 12), and the work must happen inside the same array.
Walk the array. Whenever you meet a zero, slide everything after it one step to the left and drop the zero into the last slot. The array's tail fills up with settled zeroes, so the walk can stop early.
function moveZeroes(nums) { let n = nums.length; // slots before n are still unsettled let i = 0; while (i < n) { if (nums[i] === 0) { for (let j = i; j < n - 1; j++) nums[j] = nums[j + 1]; // shift the rest left nums[n - 1] = 0; n--; // that last slot is now a settled zero } else { i++; } }}Time O(n²), space O(1). Every zero can trigger a shift of almost the whole array. An array that is half zeroes does about n²/4 moves.
Shifting is slow because the same values move again and again. Instead, collect the non-zero values in order into a temporary array, then write them back to the front of nums and fill the rest with zeroes. Every value moves exactly once.
function moveZeroes(nums) { const temp = nums.filter((x) => x !== 0); // non-zeroes, in order for (let i = 0; i < nums.length; i++) { nums[i] = i < temp.length ? temp[i] : 0; }}Time O(n), space O(n). Fast — but the temporary array is a full copy of the input, which is exactly what "in place" asks us to avoid.
Do the copying inside the same array. read looks at every element once. write points at the next slot where a non-zero value belongs. Whenever read finds a non-zero value, swap it into write and move write forward.
At every moment, everything before write is finished — non-zero values in their original order — and everything between write and read is a zero waiting to be pushed back.
Follow read and write, and watch the finished part on the left grow. Try an array with no zeroes: every swap is then an element swapping with itself.
Time O(n), space O(1). One pass, and each swap is O(1). It's as fast as the copy, with no copy at all.
O(n²)Every zero can shift almost the whole array left.
O(1)Shifting happens in place.
O(n)[3, 1, 2] stays the same.[0, 0, 0] stays the same.[1, 2, 0] is untouched.[0] or [5].The reader/writer pair is the workhorse of in-place array problems — removing values, removing duplicates, partitioning around a pivot. Whenever a problem says in place and asks you to keep some elements and drop others, reach for it first.
Two passes: copy out, then write back and pad with zeroes.
O(n)The temporary array is a full copy of the input.
O(n)One pass; each step is one O(1) swap.
O(1)Only the two pointers.