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
Binary Gap: Lighthouse Navigation1pos 01pos 21pos 31pos 4Longest Gap: 1 zeroBinary: 10110 (n = 22)1011000001Maximum Gap = 2
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
26.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen