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 inplace 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 asked 22 Sep '17, 06:13

The order of nonzero elements doesn't matter . It makes the question easier . #include <iostream> using namespace std; int main() { int a[7]={1, 0, 2, 0, 0, 3, 4 },cnt=0,temp,i,j;
} You just have to maintain a pointer from last and one from beginning to swap the nonzero elements from the end with the zero elements in the beginning . It would be really helpful if you tell how your friend got the opportunity to interview with facebook . EDIT I am counting the zero elements here . You can find the nonzero elements by subtracting the cnt from total elements . answered 22 Sep '17, 12:53
