Tutorialspoint
Problem
Solution
Submissions

Move Zeroes to End

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 5

Write a Java program to move all zeroes in an array to the end while maintaining the relative order of the non-zero elements. The operation should be done in-place with minimal operations.

Example 1
  • Input: nums = [0, 1, 0, 3, 12]
  • Output: [1, 3, 12, 0, 0]
  • Explanation:
    • Step 1: Maintain a pointer for the position where next non-zero element should be placed.
    • Step 2: Iterate through the array. When a non-zero element is found, place it at the pointer position.
    • Step 3: After all non-zero elements are positioned correctly, fill the remaining positions with zeroes.
    • Step 4: The array now has all zeroes at the end while preserving the order of non-zero elements.
Example 2
  • Input: nums = [0, 0, 1]
  • Output: [1, 0, 0]
  • Explanation:
    • Step 1: Maintain a pointer for the position where next non-zero element should be placed.
    • Step 2: Iterate through the array. The only non-zero element 1 is placed at index 0.
    • Step 3: Fill the remaining positions (indices 1 and 2) with zeroes.
    • Step 4: The array now has all zeroes at the end while preserving the order of non-zero elements.
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
  • Minimize the total number of operations
  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(1)
ArraysKPMGTutorix
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 a two-pointer technique to solve this problem
  • Keep track of the position where the next non-zero element should be placed
  • Iterate through the array once
  • When you find a non-zero element, place it at the tracked position and increment the position
  • After processing all elements, fill the remaining positions with zeroes

Steps to solve by this approach:

 Step 1: Initialize a pointer to keep track of where the next non-zero element should go.
 Step 2: Iterate through the array with another pointer.
 Step 3: If the current element is non-zero, place it at the position of the first pointer and increment it.
 Step 4: After processing all elements, all non-zero elements are now at the beginning of the array in their original order.
 Step 5: Fill the remaining positions with zeroes.
 Step 6: The array now has all zeroes moved to the end while maintaining the relative order of non-zero elements.
 Step 7: Time complexity is O(n) as we only need to iterate through the array twice.

Submitted Code :