Hello friends recently my friend went for Facebook interview and the following question was asked and the interviewer kept on drilling down for more optimized solution that too with in-place algorithm . So I would like to have a discussion here to arrive at an optimized solution
Write an algorithm that brings all nonzero elements to the left of the array, and returns the number of nonzero elements.
Example input: [ 1, 0, 2, 0, 0, 3, 4 ]
Example output: 4
[1, 4, 2, 3, 0, 0, 0]
The algorithm should operate in place, i.e. shouldn’t create a new array.
The order of nonzero elements does not matter