Tutorialspoint
Problem
Solution
Submissions

Move Zeroes

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to move all zeroes in an array to the end while maintaining the relative order of non-zero elements. The operation should be performed in-place without creating a new array.

Example 1
  • Input: nums = [0, 1, 0, 3, 12]
  • Output: [1, 3, 12, 0, 0]
  • Explanation:
    • Original array has zeroes at positions 0 and 2.
    • Non-zero elements (1, 3, 12) maintain their relative order.
    • All zeroes are moved to the end of the array.
Example 2
  • Input: nums = [0, 0, 1]
  • Output: [1, 0, 0]
  • Explanation:
    • Original array has two zeroes at the beginning.
    • The non-zero element (1) is moved to the front.
    • Both zeroes are placed at the end.
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -2^31 ≤ nums[i] ≤ 2^31 - 1
  • You must do this in-place without making a copy of the array
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysNumberCognizantWalmart
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers approach - one for writing position and one for reading
  • Iterate through the array and move non-zero elements to the front
  • Keep track of the position where the next non-zero element should be placed
  • After moving all non-zero elements, fill the remaining positions with zeroes
  • The writing pointer always stays behind or at the same position as the reading pointer

Steps to solve by this approach:

 Step 1: Initialize a writeIndex pointer to 0 to track where to place the next non-zero element.
 Step 2: Iterate through the array using a readIndex pointer from 0 to array length.
 Step 3: When a non-zero element is found, place it at the writeIndex position and increment writeIndex.
 Step 4: Continue this process until all elements are processed, ensuring non-zero elements are moved to the front.
 Step 5: Fill all remaining positions from writeIndex to the end of the array with zeroes.
 Step 6: The array is now modified in-place with all zeroes at the end.

Submitted Code :