Binary Gap (LeetCode 868): Solution and Explanation

Easy
Bit Manipulation

Return the longest distance between two adjacent 1 bits in the binary form of n, where adjacent means only 0s lie between them. Return 0 when n has fewer than two 1 bits. For n = 22 (binary 10110) the answer is 2.

Intuition

Adjacent 1s are simply consecutive 1s when you walk along the bits. So every 1 bit only needs to be compared with the 1 bit right before it.

That means one variable is enough: the position of the last 1 seen. When the next 1 shows up, the gap is the difference in positions.

Reading bits from the low end with n & 1 and n >>= 1 visits each position once, and the loop ends when n reaches 0.

Approach: Single pass with a last-1 pointer

  1. Set last = -1, best = 0 and the bit position i = 0.
  2. While n > 0, look at the lowest bit with n & 1.
  3. If it is 1 and last >= 0, set best = max(best, i - last). Then set last = i.
  4. Shift n right by one and increase i.
  5. Return best.

Step-by-step example

n = 22
  1. 22 in binary is 10110. Bit 0 is 0, so nothing happens.
  2. Bit 1 is 1. It is the first 1, so last = 1.
  3. Bit 2 is 1. Distance 2 - 1 = 1, so best = 1 and last = 2.
  4. Bit 3 is 0. Bit 4 is 1: distance 4 - 2 = 2, so best = 2 and last = 4.
  5. n is now 0, so return 2.

Code: Python, Java, C++

1class Solution:
2    def binaryGap(self, n: int) -> int:
3        last = -1
4        best = 0
5        i = 0
6        while n:
7            if n & 1:
8                if last >= 0:
9                    best = max(best, i - last)
10                last = i
11            n >>= 1
12            i += 1
13        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(log n)

The loop runs once per bit, and n has about log2(n) bits (at most 30 here).

Space

O(1)

Only three integers are stored.

Other approaches

Collect positions first (time O(log n), space O(log n))

Record the position of every 1 bit in a list, then take the largest difference between neighbours. Same time but O(log n) extra space.

Binary string (time O(log n), space O(log n))

Convert n to a binary string and scan the characters for '1', tracking the previous index. Easy to read, slightly slower because of the string.

Common mistakes

  • Counting the zeros between two 1s instead of the position difference. For 1001 there are 2 zeros but the distance is 3.
  • Starting last at 0 instead of a sentinel. Then the first 1 is measured against position 0 even when bit 0 is not a 1.
  • Measuring from the lowest bit or to the highest bit. A gap only counts when both ends are 1 bits, so trailing and leading zeros never count.

Frequently asked questions

Why is the answer 0 for a power of two?

A power of two has exactly one 1 bit, so there is no pair of 1s to measure.

What is the distance between two neighbouring 1s like in 11?

It is 1. Adjacent 1s with no zeros between them are still a valid pair, one position apart.

Does the scan direction matter?

No. Distances between consecutive 1s are the same whether you read from the high end or the low end. Reading from the low end is just the easiest with shifts.