AlgoInsight

DSA problem

Move Zeroes

EasyArraysPattern: Two Pointerstop150AmazonFacebookMicrosoftBloombergApple

Given an integer array nums, move all 0's to the end of the array while maintaining the relative order of the non-zero elements.

You must do this in-place without making a copy of the array. For example, given [0,1,0,3,12] the array should become [1,3,12,0,0].

Try to minimize the total number of operations. The optimal solution uses two pointers and performs at most one swap per element.

Examples

Example 1
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Explanation: The non-zero elements 1, 3, 12 keep their relative order and the two zeros are pushed to the end.
Example 2
Input: nums = [0]
Output: [0]
Explanation: A single zero stays in place.

Constraints

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

arraytwo-pointers

Browse all DSA problems