Skip to main content

13. Move Zeroes

easyAsked at Wise

Push zeros to the end of an array in place while preserving order — Wise treats this as a stand-in for cleaning up empty payment legs without losing real entries.

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

Problem

Given an integer array nums, move all 0s to the end of the array while preserving the relative order of the non-zero elements. The operation must be in place.

Constraints

  • 1 <= nums.length <= 10^4
  • Must be in place, no copy
  • Relative order of non-zero values preserved

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. Filter and pad

Copy non-zero values to a fresh array, then push zeros until the length matches.

Time
O(n)
Space
O(n)
const out=nums.filter(x=>x!==0);
while(out.length<nums.length) out.push(0);
for (let i=0;i<nums.length;i++) nums[i]=out[i];

Tradeoff:

2. Two-pointer in-place swap

Read pointer scans; write pointer marks the next non-zero slot. After read finishes, fill from write to end with zeros.

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

Tradeoff:

Wise-specific tips

Wise grades whether you respect in-place constraints because their batch sweepers must compact ledger rows without allocating a parallel array under load.

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

Practice these live with InterviewChamp.AI →