Similar Problems

Similar Problems not available

Sort a binary array in one iteration - Leetcode Solution

Companies:

LeetCode:  Sort a binary array in one iteration Leetcode Solution

Difficulty: Medium

Topics: sorting  

Given an array with only 0’s and 1’s , sort it in linear time.

Example Input: 1, 0, 1, 0, 1, 1, 0 0
Expected Output: 0, 0, 0, 0, 1, 1, 1, 1

This problem is similar to Move all zeros present in the array to the end and we can solve it using the same technique.

The only difference is that in the earlier problem, we were asked to move zeros to the end, in this problem we would have to move zeros to the front.

We can solve this easily by storing the index of the position where we need to store the next element and then swapping the zeros that we find as shown in the code below:

Sort a binary array in one iteration Solution Code

1