Binary Gap - Problem

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.

Input & Output

Example 1 — Basic Gap
$ Input: n = 22
Output: 1
💡 Note: 22 in binary is 10110. The gaps between consecutive 1's are: between positions 0 and 2 (gap = 1), between positions 2 and 3 (gap = 0). Maximum gap is 1.
Example 2 — No Gap
$ Input: n = 6
Output: 0
💡 Note: 6 in binary is 110. The gap between consecutive 1's at positions 0 and 1 is 0. Maximum gap is 0.
Example 3 — Power of 2
$ Input: n = 8
Output: 0
💡 Note: 8 in binary is 1000. There's only one 1, so no adjacent 1's exist. Return 0.

Constraints

  • 1 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Binary Gap - Finding Longest Distance Between 1s INPUT n = 22 Binary: 10110 1 pos 4 0 pos 3 1 pos 2 1 pos 1 0 pos 0 Positions of 1s: 4 2 1 gap=2 gap=1 Input: n = 22 Binary: 10110 ALGORITHM STEPS 1 Initialize lastPos = -1, maxGap = 0 2 Iterate bits Check each bit position 3 Find 1s Use n & 1 to check bit 4 Calculate gap gap = pos - lastPos Iteration Trace pos=1: bit=1, gap=0 pos=2: bit=1, gap=2-1=1 pos=4: bit=1, gap=4-2=2 maxGap = max(0,1,2) = 2 FINAL RESULT Longest Gap Found 1 0 1 1 0 Distance = 2 Between positions 4 and 2 Gap = 4 - 2 = 2 Output 2 OK - Verified Key Insight: Use bit manipulation (n & 1) to check each bit. Right-shift n (n >> 1) to process next bit. Track position of last seen 1. Calculate gap between consecutive 1s and keep maximum. Time: O(log n) - iterate through bits | Space: O(1) - only store position and max gap. TutorialsPoint - Binary Gap | Optimal Solution
Asked in
Google 12 Microsoft 8 Apple 5
23.4K 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