Move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example: Given A = {1,0,0,2,5,6,6,0,3,0}
Answer = {1,2,5,6,6,6,3,0,0,0,0}
Solution:
Here we would iterate through the list and we shift numbers to the left in the list. The shift happens only if the number is non-zero number.
Here we will have one runner j that gets incremented only if we don't see zero. At the end this runner(index) will be behind by the count j is behind .
Once we reached the end, we exit and started a new loop that we will put as many zeros we counted at the end starting from j.
int j = 0;
for (int i = 0; i < A.Length; i++) {
if (A[i] ! = 0) {
A[j] = A[i];
j++;
}
}
for (int i = j; i < A.Length; i++) {
A[i] = 0;
}
return A;