Explorer
JavaScript

Move all zeroes to the end of the array while maintaining the relative order of the non-zero elements.

Problem Statement

Given an integer array, move all 0s to the end of it while maintaining the relative order of the non-zero elements.

Examples

Input: arr = [0, 1, 0, 3, 12]

Output: [1, 3, 12, 0, 0]

Explanation: Zeros are pushed to the end.

Constraints

Standard constraints

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Use a two-pointer approach to keep relative order of non-zero elements. šŸ’” Hint 2: Maintain an insertPos pointer where the next non-zero element should go. šŸ’” Hint 3: Iterate through the array. When you encounter a non-zero, swap arr[i] with arr[insertPos] and advance insertPos.

Editorial & Approach

Problem Overview & Intuition

We want to shift all zeroes to the end of the array while maintaining the original relative order of non-zero elements. A single pointer tracking the next non-zero slot allows us to swap in-place in O(N) time.

Step-by-Step Approach

  1. Initialize insertPos = 0.
  2. Iterate i from 0 to arr.length - 1.
  3. Whenever arr[i] !== 0, swap arr[insertPos] and arr[i], then increment insertPos++.
  4. Return the modified arr.

Optimal Implementation (JavaScript)

function moveZeros(arr) {
  let insertPos = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 0) {
      const temp = arr[insertPos];
      arr[insertPos] = arr[i];
      arr[i] = temp;
      insertPos++;
    }
  }
  return arr;
}

Complexity Analysis

Time Complexity O(N) — single traversal of the array.
Space Complexity O(1) — in-place swapping with no secondary array.

Edge Cases & Corner Traps Handled

  • No zeroes in array: elements remain in place.
  • All zeroes in array: elements remain in place.
  • Single element [0]: returns [0].

Move Zeros to End

Easy
Given an integer array, move all 0s to the end of it while maintaining the relative order of the non-zero elements.
Example Scenarios
1Example 1
Input: arr = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Explanation:

Zeros are pushed to the end.

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[0, 1, 0, 3, 12]
Output:Click "Run" above to execute and verify your code here.
[1,3,12,0,0]