Problem Statement
You are given an array of integers, and you need to move all zeroes to the end of the array. But, you are not allowed to change the order of the non-zero elements.
Approach 1
A simple way to solve this problem is to go through the array from left to right, and every time you encounter a zero, you search the rest of the array for a non-zero to swap with it. Time Complexity : O(N^2) & Space Complexity : O(1). It's an easy algorithm and needs no extra space but it's too slow. Here is a code sample for the algorithm in C#:
- class Program
- {
- static void Main(string[] args)
- {
- int[] array = new int[] { 3, 0, 0, 1, 2, 0, 4, 0 };
- int[] result = Approach1(array);
- //result is [ 3, 1, 2, 4, 0, 0, 0, 0 ]
- }
- static int[] Approach1(int[] array)
- {
- for (int i = 0; i < array.Length; i++)
- {
- //skip non-zero elements
- if (array[i] != 0)
- continue;
- //look for the nearest non-zero
- for (int j = i + 1; j < array.Length; j++)
- {
- if (array[j] == 0)
- continue;
- //swap it with our zero
- array[i] = array[j];
- array[j] = 0;
- break;
- }
- }
- return array;
- }
- }

Anandhi RPosted Apr 3, 2022, 1:01 PM
Using System; namespace ShiftZerosToRightInArray { class Program { static void Main(string[] args) { Console.Write("Enter Array length"); int inputArrLen = Convert.ToInt32(Console.ReadLine()); int[] Arr = new int[inputArrLen]; // { 1, 4, 5, 0, 3, 7, 1, 0, 0, 11,0,12 }; Console.Write("Please enter array inputs:"); for(int i=0;i< inputArrLen;i++) { Arr[i] = Convert.ToInt32(Console.ReadLine()); } Console.WriteLine("Your Input array is :"); foreach(int row in Arr) { Console.WriteLine(row); } Console.WriteLine("We are processing your array to shift all zeros to the right.."); int ArrLen = Arr.Length; int[] result = new int[ArrLen]; int j = 0, k = ArrLen; for (int i = 0; i < ArrLen; i++) { if (Arr[i] == 0) { result[k - 1] = Arr[i]; k--; } else { result[j] = Arr[i]; j++; } } Console.WriteLine("Printing the Output"); foreach (int row in result) { Console.WriteLine("Final output is " + row); } Console.ReadKey(false); } } }
Yogesh BondiPosted Jun 29, 2021, 7:42 PM
How come in approaches 2 and 3, the time complexity is O(N). We are looping the array again, right?