Skip to main content
Back to problems
Leetcode
Easy
Strings
Arrays
Check If Binary String Has At Most One Segment Of Ones

Determine whether all the 1 characters in a binary string appear in a single contiguous block.

Acceptance 0%
Problem Statement

Check If Binary String Has At Most One Segment Of Ones

Given a binary string s containing only 0 and 1, determine whether the string contains at most one contiguous segment of 1s.

A segment of 1s is a maximal contiguous block made up entirely of 1 characters. The string is valid if it has either:

  • no 1 characters at all, or
  • exactly one block of one or more 1s.

Return true if the string is valid, otherwise return false.

Examples of valid strings

  • "0"
  • "111"
  • "0011100"

Examples of invalid strings

  • "101"
  • "110011"

Input Format

  • A single binary string s.
  • s contains only characters '0' and '1'.

Output Format

  • Return a boolean value indicating whether s has at most one segment of 1s.

Constraints

  • 1 <= s.length
  • s[i] is either '0' or '1'
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "110"

Output

true

Explanation

All the 1s are in one contiguous block at the beginning.

Example 2

Input

s = "1001"

Output

false

Explanation

There are two separate blocks of 1s: one at the start and one at the end.

Show 1 more example

Example 3

Input

s = "0000"

Output

true

Explanation

There are no 1s, so the string has at most one segment of 1s.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.