
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Move All Zeros to the End of an Array in 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]
Advertisements