Good C++ solutions to the “Bring all the zeros to the back of the array” interview challenge

Maybe the interviewer was looking for this answer:

#include <algorithm>
//...
std::partition(std::begin(arr), std::end(arr), [](int n) { return n != 0; });

If the order needs to be preserved, then std::stable_partition should be used:

#include <algorithm>
//...
std::stable_partition(std::begin(arr), std::end(arr), [](int n) { return n != 0; });

For pre C++11:

#include <functional>
#include <algorithm>
//...
std::partition(arr, arr + sizeof(arr)/sizeof(int), 
               std::bind1st(std::not_equal_to<int>(), 0));

Live Example

Basically, if the situation is that you need to move items that satisfy a condition to “one side” of a container, then the partition algorithm functions should be high up on the list of solutions to choose (if not the solution to use).

Leave a Comment