Python 1784.py
class Solution:
def checkOnesSegment(self, s: str) -> bool:
return s.find("01") == -1
Difficulty
and has an acceptance rate of about 49% (300k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a single-method solution that determines whether a binary string consists of at most one contiguous block of 1s. The method leverages the language’s built-in substring search to make the decision in a concise expression.
Key Steps
Input Reception
The method receives a string s that is expected to contain only the characters '0' and '1'. No explicit validation is performed; the method assumes the input conforms to the expected format.
def checkOnesSegment(self, s: str) -> bool:
Substring Search
The core operation uses the find method to locate the first occurrence of the pattern "01" within the input string. The pattern "01" represents a transition from a 0 to a 1, which would indicate the start of a second block of 1s after an initial block.
s.find("01")
If the pattern does not exist, find returns -1. The method then compares the result directly to -1 to produce a Boolean outcome.
Result Evaluation
The Boolean expression s.find("01") == -1 yields True when no "01" transition is found, meaning the string either contains no 1s, a single block of 1s, or consists solely of 1s. Conversely, the presence of any "01" transition leads to False.
return s.find("01") == -1
Edge Cases Handled
When the input string is empty, the find operation returns -1, and the method correctly returns True because an empty string trivially satisfies the “single block” condition.
A string composed entirely of 0s also lacks the "01" pattern, resulting in a True return value, which aligns with the definition that zero occurrences of 1 are acceptable.
A string composed entirely of 1s contains no transition from 0 to 1, so the method returns True. This covers the scenario where the block of 1s starts at the first character.
Strings that contain a single transition from 1 to 0 (e.g., "1100") do not introduce a "01" pattern, and the method returns True. This reflects the fact that the block of 1s ends and no new block begins.
Strings with multiple alternating segments, such as "10101" or "110011", contain at least one "01" transition after an initial block of 1s, causing find to return a non-negative index and the method to return False.
Performance Optimizations
The implementation relies on the native find method, which is highly optimized in the interpreter’s core. This built-in routine typically employs efficient search algorithms that operate directly on the underlying memory representation of the string, minimizing overhead compared to a manual iteration.
By checking for the specific transition "01" rather than scanning for all possible patterns, the method reduces the amount of work needed to determine the answer. The moment a "01" sequence is encountered, the search can terminate early, providing an implicit short-circuit behavior.
The final Boolean comparison is performed without any additional branching or temporary variables, resulting in a compact execution path that benefits from the interpreter’s ability to inline simple expressions.
Overall, the solution achieves its goal with minimal code and leverages the language’s optimized primitives to deliver fast, low-overhead execution for strings of any length.
ELI5 - Simplified Explanation
Imagine a long train track made of many little pieces snapped together in a row. Some pieces are ones and some pieces are zeros. The goal is to see if all the pieces labeled as one are sitting together in a single group without any zeros trying to break them apart. When the computer looks at the string of pieces, it specifically hunts for a spot where a zero is holding hands with a one right after it. Finding that specific combination means that a zero has snuck in to split the ones into two different groups. If the computer searches the whole track and cannot find that sneaky spot, it means everything is perfect and all the ones are together in one big line.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
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++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | JS | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 1869: Longer Contiguous Segments of Ones than Zeros
Solved On The Same Day
- problem 1013: Partition Array Into Three Parts With Equal Sum
- problem 1668: Maximum Repeating Substring
- problem 1736: Latest Time by Replacing Hidden Digits
- problem 2099: Find Subsequence of Length K With the Largest Sum
- problem 2383: Minimum Hours of Training to Win a Competition
- problem 2511: Maximum Enemy Forts That Can Be Captured
- problem 2739: Total Distance Traveled
- problem 331: Verify Preorder Serialization of a Binary Tree
- problem 400: Nth Digit
- problem 447: Number of Boomerangs
- problem 1476: Subrectangle Queries
- problem 1828: Queries on Number of Points Inside a Circle
Extra
- 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