Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to partition bits in a bit array with less than linear time

Tags:

c++

This is an interview question I faced recently.


Given an array of 1 and 0, find a way to partition the bits in place so that 0's are grouped together, and 1's are grouped together. It does not matter whether 1's are ahead of 0's or 0's are ahead of 1's.

An example input is 101010101, and output is either 111110000 or 000011111.

Solve the problem in less than linear time.

Make the problem simpler. The input is an integer array, with each element either 1 or 0. Output is the same integer array with integers partitioned well.


To me, this is an easy question if it can be solved in O(N). My approach is to use two pointers, starting from both ends of the array. Increases and decreases each pointer; if it does not point to the correct integer, swap the two.

    int * start = array;
    int * end = array + length - 1;

    while (start &lt end) {
        // Assume 0 always at the end
        if (*end == 0) {
            --end; 
            continue;
        }

        // Assume 1 always at the beginning
        if (*start == 1) {
            ++start; 
            continue;
        }

        swap(*start, *end);
    }

However, the interview insists there is a sub-linear solution. This makes me thinking hard but still not get an answer.

Can anyone help on this interview question?

UPDATE: Seeing replies in SO stating that the problem cannot be solved in sub-linear time, I can confirm my original idea that there cannot be a solution of sub-linear.

Is it possible the interviewer plays a trick?

like image 315
SiLent SoNG Avatar asked Mar 17 '10 07:03

SiLent SoNG


1 Answers

I don't see how there can be a solution faster than linear time.

Imagine a bit array that is all 1's. Any solution will require examining every bit in this array before declaring that it is already partitioned. Examining every bit takes linear time.

like image 80
Brandon Bodnar Avatar answered Nov 02 '22 22:11

Brandon Bodnar