Skip to main content
Back to problems
Leetcode
Medium
Arrays
Two Pointers
Greedy
Move Zeroes

Move all zeroes to the end of the array while preserving the relative order of the non-zero elements.

Acceptance 86%
Problem Statement

Problem

Given an integer array, reorder it in place so that all 0 values are moved to the end while the relative order of the non-zero values remains unchanged.

You must modify the array directly and avoid using extra space proportional to the input size.

Goal

After the transformation:

  • every non-zero element should appear before every zero
  • the non-zero elements should stay in their original order
  • the array length must remain the same

Input Format

  • A list of integers nums
  • The array may contain positive, negative, and zero values

Output Format

  • Modify nums in place
  • Return nothing, or return the modified array depending on the language convention

Constraints

  • 1nums.length1 \le nums.length
  • Elements may be any 32-bit signed integers
  • Aim for O(n)O(n) time and O(1)O(1) extra space
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [0,1,0,3,12]

Output

[1,3,12,0,0]

Explanation

The non-zero values 1, 3, and 12 keep their original order, and the zeroes are moved to the end.

Example 2

Input

nums = [0,0,1]

Output

[1,0,0]

Explanation

Only one non-zero value exists, so it is placed first and the zeroes follow.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.