diff --git a/Arrays/move_zeros_to_last.cpp b/Arrays/move_zeros_to_last.cpp new file mode 100644 index 0000000..be008e9 --- /dev/null +++ b/Arrays/move_zeros_to_last.cpp @@ -0,0 +1,52 @@ +/* +Question: Given an array of random numbers move all zeros of array to the end +Approach/Algo: +Step 1: Iterate through the array from left to right and maintain count of non-zero elements +Step 2: The element other than 0 i.e arr[i], put the element at arr[count] and increment count +Step 3: The count will be at first 0 element, just iterate a loop to end and make element zero. +*/ + + +#include +using namespace std; + +void pushZerosToEnd(int arr[], int n) +{ + int count = 0; + for (int i = 0; i < n; i++) + if (arr[i] != 0) + arr[count++] = arr[i]; + + for(int j=count;j (Since looping through the array of n element) +Space complexity: O(1) +*/ \ No newline at end of file