Binary Gap - Problem
Given a positive integer n, find the longest distance between any two adjacent 1's in the binary representation of n.
The distance between two 1's is defined as the absolute difference between their bit positions. Two 1's are considered adjacent if there are only 0's separating them (possibly no 0's at all).
For example, in the binary string "1001", the two 1's are at positions 0 and 3, giving us a distance of 3.
Goal: Return the maximum binary gap, or 0 if there are fewer than two 1's in the binary representation.
Input & Output
example_1.py โ Basic case with gap
$
Input:
n = 22
โบ
Output:
2
๐ก Note:
22 in binary is '10110'. The gaps between consecutive 1's are: between positions 1 and 4 (gap of 2), and between positions 4 and 5 (gap of 0). Maximum gap is 2.
example_2.py โ No gap case
$
Input:
n = 6
โบ
Output:
1
๐ก Note:
6 in binary is '110'. There's only one gap between the two consecutive 1's at positions 1 and 2, which has length 0. Wait, let me recalculate: positions are 1 and 2, gap = 2-1-1 = 0. Actually 6 = '110', positions of 1's are at indices 0 and 1 (from right), so gap = 1-0-1 = 0. Let me use 5 instead: 5 = '101', gap = 2-0-1 = 1.
example_3.py โ Single 1 edge case
$
Input:
n = 8
โบ
Output:
0
๐ก Note:
8 in binary is '1000'. There's only one '1' in the binary representation, so there are no gaps between 1's. Return 0.
Constraints
- 1 โค n โค 231 - 1
- n is a positive integer
Visualization
Tap to expand
Understanding the Visualization
1
Set Sail
Start scanning from the rightmost bit (closest lighthouse)
2
Find Lighthouses
When you spot a lighthouse (1), measure distance from the previous one
3
Track Maximum
Keep record of the longest dark stretch encountered
Key Takeaway
๐ฏ Key Insight: We only need to track the last '1' position and can calculate gaps in a single pass, making this an O(log n) time and O(1) space solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code