Tutorialspoint
Problem
Solution
Submissions

Move Zeroes

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

Write a C program to move all zeros to the end of an array. Given an integer array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.

Note that you must modify the array in-place and not allocate extra space for another array.

Example 1
  • Input: nums = [0,1,0,3,12]
  • Output: [1,3,12,0,0]
  • Explanation:
    We need to move all zeros to the end while keeping the order of non-zero elements.
    Starting with [0,1,0,3,12], after moving all non-zero elements to the front and filling the rest with zeros, we get [1,3,12,0,0].
Example 2
  • Input: nums = [0]
  • Output: [0]
  • Explanation:
    Array contains only one element which is already 0.
    No changes needed as zero is already at the end.
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -2^31 ≤ nums[i] ≤ 2^31 - 1
  • You must perform operations in-place with O(1) extra memory
  • Time Complexity: O(n) where n is the length of the array
  • Space Complexity: O(1)
ArraysHCL TechnologiesSwiggy
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 approach to solve this problem
  • Keep track of the position where the next non-zero element should be placed
  • Iterate through the array, moving non-zero elements to their correct positions
  • After placing all non-zero elements, fill the remaining positions with zeros
  • Make sure you don't create unnecessary swaps if the element is already in the correct position

Steps to solve by this approach:

 Step 1: Initialize a pointer nonZeroPos to 0, which will track where the next non-zero element should go.
 Step 2: Iterate through the array with index i from 0 to numsSize-1.
 Step 3: Whenever a non-zero element is encountered at index i, place it at position nonZeroPos.
 Step 4: Increment nonZeroPos after placing each non-zero element.
 Step 5: After processing all elements, fill all positions from nonZeroPos to the end of the array with zeros.
 Step 6: This approach maintains the relative order of non-zero elements while moving all zeros to the end.
 Step 7: The array is modified in-place with O(1) extra space.

Submitted Code :