Skip to main content

18. Move Zeroes

easyAsked at Square

Push zero-amount line items to the end of a POS receipt array while keeping non-zero charges in order — Square's receipt-rendering pipeline compacts voided items in-place before printing, without allocating a second buffer.

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

Problem

Given an integer array nums, move all 0s to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of 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. Extra array

Collect non-zeroes into a new array, then fill zeroes. Correct but violates the in-place requirement.

Time
O(n)
Space
O(n)
function moveZeroes(nums) {
  const nonZero = nums.filter(n => n !== 0);
  for (let i = 0; i < nums.length; i++) {
    nums[i] = i < nonZero.length ? nonZero[i] : 0;
  }
}

Tradeoff:

2. Two-pointer in-place

Slow pointer marks the next write position; fast pointer scans. When fast finds a non-zero, write it to slow and advance slow. Then fill tail with zeroes. Minimizes writes.

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

Tradeoff:

Square-specific tips

Square cares about minimizing write operations here — the follow-up is 'can you reduce swaps?' The two-pointer approach that overwrites then fills zeros beats a swap-based approach by roughly half the writes on sparse arrays. Say that explicitly; they grade communication of tradeoffs as much as the code itself.

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 Square interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →