Skip to main content

13. Move Zeroes

easyAsked at Coupang

Move all zeroes to the end of an array while preserving the order of non-zeros, mirroring how Coupang's returns processing pushes invalidated SKUs to a quarantine tail without rewriting the active inventory.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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 without copying the array.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Examples

Example 1

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

Example 2

Input
nums=[0]
Output
[0]

Approaches

1. Two passes with shifting

Copy non-zeros forward, then pad zeros.

Time
O(n)
Space
O(1)
let w = 0;
for (const n of nums) if (n !== 0) nums[w++] = n;
while (w < nums.length) nums[w++] = 0;

Tradeoff:

2. Two-pointer swap

Walk a write pointer with a read pointer; swap on non-zero.

Time
O(n)
Space
O(1)
function moveZeroes(nums) {
  let w = 0;
  for (let r = 0; r < nums.length; r++) {
    if (nums[r] !== 0) {
      [nums[w], nums[r]] = [nums[r], nums[w]];
      w++;
    }
  }
}

Tradeoff:

Coupang-specific tips

Coupang returns-processing pushes invalidated SKUs to a quarantine tail in-place; the swap-based pattern is a closer match than the copy-then-pad version.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Move Zeroes and other Coupang interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →