DSA-VerseLearn by watching code run
DashboardData StructuresAlgorithmsVisualizerCORECoding PlaygroundInterview QuestionsComplexity AnalyzerLearning NotesBookmarksLearning ProgressSettings
All interview questions

Interview preparation

Move Zeroes

EasyArrays
MetaAmazon Community-reported practice tags — not verified company questions.

1Problem statement

Given an integer array nums, move all 0s to the end while keeping the relative order of the non-zero elements. Do it in place.

2Examples

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

3Constraints

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

4Approaches

Approach 1

Brute Force

Copy non-zeros into a new array, then fill the rest with zeros and copy back.

Time O(n)Space O(n)

Approach 2

Better: Overwrite then fill

Write non-zeros forward with an index, then fill the tail with zeros.

Time O(n)Space O(1)

Approach 3

Optimal: Two-pointer swap

Pointer `write` marks the next slot for a non-zero; swap each non-zero into it. Minimises writes.

Time O(n)Space O(1)

5Code (optimal approach)

Complete programs that print the example outputs — verified in JavaScript, Python, Java and Go.

function moveZeroes(nums) {
  let write = 0;
  for (let read = 0; read < nums.length; read++) {
    if (nums[read] !== 0) {
      [nums[write], nums[read]] = [nums[read], nums[write]];
      write++;
    }
  }
  return nums;
}

console.log(moveZeroes([0, 1, 0, 3, 12]));
console.log(moveZeroes([0]));

6Complexity

Time

O(n)

Space

O(1)

7Visual walkthrough

  1. 1.write = 0
  2. 2.read 0 → skip
  3. 3.read 1 → swap into 0 → [1, 0, 0, 3, 12], write = 1
  4. 4.read 3 → swap → [1, 3, 0, 0, 12], write = 2
  5. 5.read 12 → swap → [1, 3, 12, 0, 0]

Related visualization (Reverse an Array) — shows the core data-structure operations this solution relies on:

Reverse an Arrayinteractive Open full visualizer
1
2
3
4
5
6
0
1
2
3
4
5
ComparingSwapping / movingCurrentSorted / finalFound / placed

Reverses an array in place with two pointers: swap the outermost pair, move both pointers inward, and stop when they meet.

1 / 17

8Related questions

Two Sum

On this page

  1. 01Problem statement
  2. 02Examples
  3. 03Constraints
  4. 04Approaches
  5. 05Code (4 languages)
  6. 06Complexity
  7. 07Visual walkthrough
  8. 08Related questions