Leetcode 1784: Check if Binary String Has at Most One Segment of Ones

grid47
grid47
Exploring patterns and algorithms
May 12, 2024 3 min read

Given a binary string s without leading zeros, return true if the string contains at most one contiguous block of 1s. Otherwise, return false.
Problem
Approach
Steps
Complexity
Input: You are given a binary string s that does not have leading zeros. The string is made up of '0's and '1's.
Example: s = '101'
Constraints:
• 1 <= s.length <= 100
• s[i] is either '0' or '1'
• s[0] is '1'
Output: Return true if the string contains at most one contiguous block of '1's. Otherwise, return false.
Example: Input: s = '111', Output: true
Constraints:
Goal: The goal is to determine if there is only one contiguous block of '1's in the string.
Steps:
• 1. Search for the substring '01' in the string.
• 2. If the substring '01' is found, return false since there are multiple blocks of '1's.
• 3. If no such substring is found, return true as the '1's form one contiguous block.
Goal: The binary string s must not have leading zeros and the length must be between 1 and 100.
Steps:
• 1 <= s.length <= 100
• s[i] is either '0' or '1'
• s[0] is '1'
Assumptions:
• The binary string s starts with a '1'.
• The string contains only '0's and '1's.
Input: Input: s = '101'
Explanation: The ones in the string are not contiguous, as there is a '0' between them. Hence, the result is false.

Input: Input: s = '111'
Explanation: The ones form a single contiguous block, so the result is true.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus