↓Skip to main content
  1. LeetCode/

LeetCode 868: Binary Gap

·2 mins· ·
LeetCode Easy Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-17

  • Submissions: Runtime Error ×2 → Wrong Answer ×5 → Accepted

Approach
#

Scan from the lowest bit (Bit Manipulation), remembering the last 1’s position last; at each new 1 the distance is i - last, and keep the maximum. With a single 1 the answer is 0.

My Attempts
#

The early versions found the longest run of 0s via s.split('1') and added 1:

  • Trailing zeros were counted, though no 1 follows them: 24 (11000) returned 4 instead of 1.
  • After strip('0'), adjacent 1s are 1 apart but split into an empty string of length 0: 7 (111) returned 0, and 5 (101) stayed off by one.

Recording the positions of the 1s passed.

Solution
#

class Solution:
    def binaryGap(self, n: int) -> int:
        last, best, i = -1, 0, 0
        while n:
            if n & 1:
                if last >= 0:
                    best = max(best, i - last)
                last = i
            n >>= 1
            i += 1
        return best

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • The distance is the difference of positions: adjacent 1s are 1 apart, not 0.
  • Trailing zeros have no 1 after them and form no gap.

Interview Explanation
#

Scanning bits from the lowest, I remember the previous 1’s position and update the maximum distance at each new 1. Time O(log n), space O(1).

Related

LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 693: Binary Number with Alternating Bits
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 693 note: alternating bits means the binary string has neither 00 nor 11; in bits, n ^ (n » 1) is all ones
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set
LeetCode 476: Number Complement
·1 min
LeetCode Easy Bit-Manipulation
LeetCode 476 note: build an all-ones mask as long as num; num ^ mask is the complement
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains