#283EasyTwo Pointers

Move Zeroes

Move all zeroes to the end while preserving non-zero element order.

FacebookMicrosoftBloombergUber

Problem Statement

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place.

Examples

Example 1

Input:nums = [0,1,0,3,12]
Output:[1,3,12,0,0]

Example 2

Input:nums = [0]
Output:[0]

Constraints

  • 1 ≤ nums.length ≤ 10⁴
  • -2³¹ ≤ nums[i] ≤ 2³¹ − 1

Solutions

1
Extra Array
TimeO(n)SpaceO(n)

Copy non-zero elements to a new array, then fill the remaining positions with zeros, and copy back. Uses extra space.

Visual Animation
def moveZeroes(nums: list[int]) -> None:
    result = [x for x in nums if x != 0]
    result += [0] * (len(nums) - len(result))
    nums[:] = result

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Two Pointers to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems