Binary Gap Problem
Description
LeetCode Problem 868.
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in "1001" have a distance of 3.
Example 1:
Input: n = 22
Output: 2
Explanation: 22 in binary is "10110".
The first adjacent pair of 1's is "10110" with a distance of 2.
The second adjacent pair of 1's is "10110" with a distance of 1.
The answer is the largest of these two distances, which is 2.
Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.
Example 2:
Input: n = 5
Output: 2
Explanation: 5 in binary is "101".
Example 3:
Input: n = 6
Output: 1
Explanation: 6 in binary is "110".
Example 4:
Input: n = 8
Output: 0
Explanation: 8 in binary is "1000".
There aren't any adjacent pairs of 1's in the binary representation of 8, so we return 0.
Example 5:
Input: n = 1
Output: 0
Constraints:
- 1 <= n <= 10^9
Solution
Approach: One Pass over the Bits
Two 1's are "adjacent" exactly when they are consecutive 1's in the binary representation. So the answer is the largest distance between each 1 and the 1 just before it, and a single scan over the bits finds it.
- Read the bits from the lowest upward: look at
n & 1, then shiftnright by one, counting the bitposition. - Keep
lastOne, the position of the most recent 1 bit seen (start at-1, meaning none yet). - At each 1 bit: if
lastOneis set, updatelongestwithposition - lastOne; then setlastOne = position.
The edge case is a number with a single 1 bit, such as 8 (1000) or 1: no pair exists and the answer is 0. Starting lastOne at -1 and only measuring once a previous 1 exists handles this; measuring from position 0 instead would wrongly report a distance of 3 for 8.
Complexity: O(log n) time, one step per bit of n (at most 30 bits), and O(1) space.
class Solution:
def binaryGap(self, n: int) -> int:
longest = 0
last_one = -1 # position of the previous 1 bit, -1 until we see one
position = 0
while n > 0:
if n & 1:
if last_one != -1:
longest = max(longest, position - last_one)
last_one = position
n >>= 1
position += 1
return longest
Now write it from memory
Close the write-up and solve it yourself against the tests.