How to move all the zeros to the end of the array from the given array of integer numbers using C#?


Create a method MoveZeros, traverse through the array and count the number of Zeros in the array. Based on the count size make all the final cells to zero. Return without processing if the array length is null or empty. The final result will be in nums Array. Time complexity is O(N) because we are traversing through the array once.

Time complexity − O(N)

Space complexity − O(1)

Example

public class Arrays{
   public void MoveZeros(int[] nums){
      if (nums == null || nums.Length == 0){
         return;
      }
      int count = 0;
      for (int i = 0; i < nums.Count(); i++){
         if (nums[i] != 0){
            nums[count] = nums[i];
            count++;
         }
      }
      for (int i = count; i < nums.Length; i++){
         nums[i] = 0;
      }
   }
}

static void Main(string[] args){
   int[] nums = { 0, 1, 0, 3, 12 };
   s.MoveZeros(nums);
   foreach (var item in nums){
      Console.WriteLine(item);
   }
}

Output

[1,3,12,0,0]

Updated on: 17-Aug-2021

500 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements