Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Write a function that moves all zeroes to the end of an array while keeping the order of the other elements.

SHORT ANSWER

Use a write pointer: copy every non-zero value forward to the write position, then fill the remaining slots with zeroes. One pass, no extra array.

Explain it simply

Picture a queue at a railway ticket counter where some people are only holding a place for someone else (the zeroes). You walk down the line and ask each real passenger to step forward into the earliest free spot. When you reach the end, everyone who is left over is a placeholder and stands at the back.

Two pointers do this: read scans every element, and write marks the next spot for a non-zero value.

Example

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

console.log(moveZeroes([0, 1, 0, 3, 12])); // Output: [1,3,12,0,0]
console.log(moveZeroes([0, 0, 5])); // Output: [5,0,0]

Complexity

Time O(n), space O(1).

What to say in the interview

"I would use two pointers. The read pointer walks the whole array, and the write pointer tracks where the next non-zero value belongs. After the scan I fill the rest with zeroes. It is in place, keeps the relative order, and runs in O(n) time with O(1) extra space."

Common mistakes

  • Sorting the array to push zeroes back: that is O(n log n) and breaks the original order of the other numbers.
  • Creating a new array when the question asks for an in-place change.

#arrays#two-pointers

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.