Binary Gap (LeetCode 868): Solution and Explanation
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
- Set
last = -1,best = 0and the bit positioni = 0. - While
n > 0, look at the lowest bit withn & 1. - If it is 1 and
last >= 0, setbest = max(best, i - last). Then setlast = i. - Shift
nright by one and increasei. - Return
best.
Step-by-step example
n = 22
- 22 in binary is 10110. Bit 0 is 0, so nothing happens.
- Bit 1 is 1. It is the first 1, so last = 1.
- Bit 2 is 1. Distance 2 - 1 = 1, so best = 1 and last = 2.
- Bit 3 is 0. Bit 4 is 1: distance 4 - 2 = 2, so best = 2 and last = 4.
- 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 best1class Solution {
2 public int binaryGap(int n) {
3 int last = -1, best = 0;
4 for (int i = 0; n > 0; i++) {
5 if ((n & 1) == 1) {
6 if (last >= 0) {
7 best = Math.max(best, i - last);
8 }
9 last = i;
10 }
11 n >>= 1;
12 }
13 return best;
14 }
15}1class Solution {
2public:
3 int binaryGap(int n) {
4 int last = -1, best = 0;
5 for (int i = 0; n > 0; i++) {
6 if (n & 1) {
7 if (last >= 0) {
8 best = max(best, i - last);
9 }
10 last = i;
11 }
12 n >>= 1;
13 }
14 return best;
15 }
16};Time and space complexity
O(log n)
The loop runs once per bit, and n has about log2(n) bits (at most 30 here).
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
1001there are 2 zeros but the distance is 3. - Starting
lastat 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.