Problem 868

Abstract / Summary

Find the longest distance between two 1s in the binary representation of a number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0868.py

class Solution:
    def binaryGap(self, n: int) -> int:
        b = bin(n)
        b = b[2:]        # strip "0b"
        b = b.strip("0") # no trailing zeros

        if b == "1":
            return 0 # only one set bit

        for result in range(len(b)):
            if b.find("0" * result) == -1:
                return result
12 lines | 343 bytes | submitted October 8, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (200k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method binaryGap. The method receives a non-negative integer n and returns the length of the longest distance between two consecutive 1 bits in the binary representation of n. The algorithm works by converting the integer to a binary string, trimming irrelevant characters, and then searching for the smallest number of consecutive zeros that does not appear in the processed string. The returned value corresponds to the maximal gap between set bits.

Key Steps

Converting the integer to a binary string

b = bin(n)
b = b[2:]        # strip "0b"

The built-in bin function yields a string prefixed with "0b". Slicing removes the prefix, leaving only the raw binary digits. This step prepares the data for subsequent string manipulation without any arithmetic operations.

Removing trailing zeros

b = b.strip("0") # no trailing zeros

Trailing zeros cannot be part of a gap between two 1 bits because a gap is defined by the distance from one 1 to the next 1. By stripping any trailing zeros, the algorithm guarantees that the final character of b is always a 1 (unless the original number is zero, which is handled implicitly). This reduction simplifies the search for gaps.

Handling the single-bit edge case

if b == "1":
    return 0 # only one set bit

When the binary representation consists of a solitary 1, there is no second 1 to form a gap. The method returns 0 immediately, covering the edge case where n is a power of two (e.g., 1, 2, 4, 8, …) after the trailing zeros have been stripped.

Searching for the minimal missing zero-run length

for result in range(len(b)):
    if b.find("0" * result) == -1:
        return result

The loop iterates over possible gap lengths from 0 up to the length of the processed string. For each candidate result, it constructs a string consisting of result consecutive zeros ("0" * result) and checks whether this pattern occurs anywhere in b. The first length that does not appear corresponds to the longest distance between two 1 bits, because any smaller distance would have been observed as a run of zeros between two 1s. The method returns this length as soon as it is identified, providing an early exit from the loop.

Edge Cases Addressed

The code explicitly handles the situation where the binary representation contains only a single 1. By stripping trailing zeros, it also implicitly deals with inputs that are zero (n = 0). In that case, bin(0) yields "0b0", the slice produces "0", and strip("0") results in an empty string. The subsequent comparison b == "1" fails, and the loop runs with len(b) == 0. The range is empty, so the function implicitly returns None. However, given the problem constraints that n is positive, the primary edge case of a solitary set bit is the one explicitly covered.

Another subtle edge case is when the binary string ends with a series of zeros. By stripping those zeros, the algorithm ensures that the final character is a 1, preventing a false detection of a larger gap that would otherwise be created by the trailing zeros.

Performance Optimizations

The implementation leverages Python’s highly optimized built-in string operations. Converting the integer to a binary string with bin and slicing off the prefix is a constant-time operation relative to the size of the integer’s bit length. The strip method removes all trailing zeros in a single pass, avoiding the need for manual iteration.

The core search loop uses str.find, which is implemented in C and benefits from efficient substring search algorithms. By constructing the zero-run pattern ("0" * result) only once per iteration and immediately checking its presence, the algorithm avoids nested loops or explicit character-by-character scanning. The early return upon finding the first missing pattern eliminates unnecessary iterations, especially for numbers with small gaps.

Overall, the code relies on native string handling to achieve concise and fast execution without resorting to explicit bitwise manipulation or additional data structures.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long string of beads, where some are red and some are blue. The computer looks at a number and turns it into a line of ones and zeros, kind of like a secret code. First, the code cleans up the secret code by removing some fluff at the beginning and the end so there is only important stuff left. If the code is just a single one, it stops because there are no gaps to measure. Otherwise, it starts counting how many zeros are hiding between the ones. It keeps checking to see if there is a long row of zeros inside the line. As soon as it finds the longest row of zeros that fits, it has the answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 3.96 | σ = 1.82

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS C# Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
withaarzoo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
withaarzoo C++
zfang399 C++
40 links | 24 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

4 solutions   October 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality