Twitter Codility Problem – Max Binary Gap

Problem: Get maximum binary Gap.

For example, 9's binary form is 1001, the gap is 2.

Java Solution 1

An integer x & 1 will get the last digit of the integer.

public static int getGap(int N) {
	int max = 0;
	int count = -1;
	int r = 0;
 
	while (N > 0) {
		// get right most bit & shift right
		r = N & 1;
		N = N >> 1;
 
		if (0 == r && count >= 0) {
			count++;
		}
 
		if (1 == r) {
			max = count > max ? count : max;
			count = 0;
		}
	}
 
	return max;
}

Time is O(n).

Java Solution 2

public static int getGap(int N) {
	int pre = -1;
	int len = 0;
 
	while (N > 0) {
		int k = N & -N;
 
		int curr = (int) Math.log(k);
 
		N = N & (N - 1);
 
		if (pre != -1 && Math.abs(curr - pre) > len) {
			len = Math.abs(curr - pre) + 1;
		}
		pre = curr;
	}
 
	return len;
}

Time is O(log(n)).

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Vivek Venkatesh

    Java solution 2 doesn’t give the expected out. Len is Math.abs(curr-pre) – 1 and not + 1.

    public static int getGap(int N) {
    int pre = -1;
    int len = 0;

    while (N > 0) {
    int k = N & -N;

    int curr = (int) Math.log(k);

    N = N & (N – 1);

    if (pre != -1 && (Math.abs(curr – pre) – 1) > len) {
    len = Math.abs(curr – pre) – 1;
    }
    pre = curr;
    }

    return len;
    }

  • Shaiar

    N is the decimal number. The number of bits used to represent it is Log2(N), so any algorithm going through all bits once is O(log N) when N is the decimal number.

  • Shawn

    How can we do this in O(log(N)) time? I passed all the correctness tests with an O(N) algorithm where N is the number of bits required to represent the number, but the test says expected time complexity is log(N).

  • Pulkit Agarwal

    Algorithm:

    1. Initially leftIndex = 0 and rightIndex = 0;

    2. Isolate the rightmost set bit. ( n & -n )
    3. Taking a log2 would give the position K. rightIndex = K

    4. No. of 0s or gaps = rightIndex – leftIndex -1;
    5. leftIndex = rightIndex;
    6. Unset the rightmost set bit. ( n & n-1).
    7. Repeat from step 1 with the new number got at 6.

    This algorithm will run in O(m) where m = no. of set bits.