Problem 1784

Abstract / Summary

Check if a binary string contains zero or one continuous group of 1s.

Note

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

Python 1784.py

class Solution:
    def checkOnesSegment(self, s: str) -> bool:
        return s.find("01") == -1
3 lines | 101 bytes | submitted October 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (300k+ submissions).

Typical patterns to solve this problem:
  • String
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 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.

written by openai gpt

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.

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 = 9 | μ = 8.41 | σ = 1.79

Complexity Analysis

Time: linear
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
generated automatically

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++ 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++
30 links | 17 authors | 9 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

13 solutions   October 12, 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