AlgoInsight

DSA problem

Move All Zeroes to the End

EasyArraysPattern: Two PointersbeginnerFreeMetaBloomberg

Given an array of N integers, move all zeroes to the end while maintaining the relative order of the non-zero elements. Do this in-place.

Use a write pointer that tracks where the next non-zero element should go. Iterate with a read pointer: whenever you find a non-zero element, place it at the write pointer's position and advance the write pointer. After the loop, fill the remaining positions with zeroes.

Both this and the swap-based variant are O(N) time, O(1) space. It tests your ability to rearrange elements in-place while preserving order - a skill needed for partition-based algorithms like quicksort.

Examples

Example 1
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Explanation: Non-zero values keep their order at the front; the two zeroes are pushed to the end.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

array

Browse all DSA problems