Posts Segregate 0s and 1s in an array (InterviewBit)
Post
Cancel

Segregate 0s and 1s in an array (InterviewBit)

PROBLEM DESCRIPTION

You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array [Basically you have to sort the array]. Traverse array only once.

InterviewBit

SOLUTION

This is a pretty simple one. First find the count of zeroes. Then, fill the complete array with 1. The first half needs to be zeroes. So, loop from left and start adding the zeroes based on the count calculated earlier.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {

    public int[] solve(int[] A) {

        int n = A.length;

        int count0 = 0;

        for(int i=0; i<n; i++){
            if(A[i] == 0) count0++;
        }

        Arrays.fill(A, 1);

        for(int i=0; i<count0; i++){
            A[i] = 0;
        }

        return A;

    }

}
This post is licensed under CC BY 4.0 by the author.