Two Pointer · Easy

Move Zeroes to the End

Solve it on DeVert Campus - free code runner

Problem

You are given an array of n integers. Rearrange the array in place so that all zero values are moved to the end while all non-zero values keep their original relative order. Report the resulting array.

Input and output

Input: The first line contains the integer n. The second line contains n space-separated integers. Output: Print the n integers of the rearranged array, space-separated, on a single line.

Example

Input:
5
0 1 0 3 12
Output:
1 3 12 0 0

Constraints

1 <= n <= 10^5 -10^9 <= arr[i] <= 10^9

Key observation

This is the SAME 'write pointer trails a scanning pointer' template as 'Remove Duplicates from Sorted Array' - recognizing the shared shape across both problems (compact desired values forward, leaving the rest for later) builds transferable two-pointer intuition.

Intuition

Move all zero values in an array to the end, while keeping the non-zero values in their original relative order. Brute force: Build a separate output array, first copying all non-zero values, then appending zeros - this works but uses O(n) extra space, when an in-place two-pointer approach needs none. Optimised: Tracking a single 'next non-zero write position' marker and overwriting the array with non-zero values in a single left-to-right pass compacts everything correctly - since every non-zero value's relative order is preserved by writing them in the SAME order they're encountered, and filling the remainder with zeros afterward completes the rearrangement in place.

Step by step

1. Keep a pointer marking the NEXT position where a non-zero value should be placed, starting at index 0. 2. Scan the array left to right; every time you see a NON-ZERO value, place it at the marker position and advance the marker. 3. After the scan, every position from the marker to the end of the array should be filled with zero.

Complexity

Time: O(n) - a single pass to place non-zeros, plus a final pass (or combined logic) to fill the remaining zeros. Space: O(1) extra space - the array is modified in place.

Edge cases

Handle an array with no zeros (order unchanged) and an array that is entirely zeros (still all zeros); the pass must be a single O(n) scan at n = 10^5.

Interview tip

Be ready to mention the alternative 'swap' variant (swapping the current element with the marker position whenever a non-zero is found, rather than always writing then filling zeros afterward) - both achieve the same result, just with slightly different bookkeeping.

All DSA problems