Given an array of random numbers, Push all the zero’s of a given array to the end of the array
Example:
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0, 0};
Input : arr[] = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
First, we discuss strategies and edge cases to handle then we study the approach that is:-
if the current element is non-zero, place the element at the next available position in the array. After all elements in the array are processed, fill all remaining indices by 0.
Steps:
k = 0
for i in A:
if I != 0:
A[k] = i
k = k + 1
for i in range(k, len(A)):
A[i] = 0