Advertisement

Check if Binary String Has at Most One Segment of Ones - LeetCode 1784 Solution

Check if Binary String Has at Most One Segment of Ones - Complete Solution Guide

Check if Binary String Has at Most One Segment of Ones is LeetCode problem 1784, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given a binary string s ​​​​​without leading zeros , return true ​​​ if s contains at most one contiguous segment of ones . Otherwise, return false . Example 1: Input: s = "1001" Output: false Explanation: The ones do not form a contiguous segment. Example 2: Input: s = "110" Output: true Constraints: 1 <= s.length <= 100 s[i] ​​​​ is either '0' or '1' . s[0] is '1' .

Detailed Explanation

The problem asks you to determine if a binary string (a string containing only '0's and '1's) has at most one contiguous segment of ones. A contiguous segment of ones means a sequence of one or more consecutive '1's. The input string is guaranteed to start with '1' and not contain leading zeros. The output is a boolean value: `true` if there's at most one contiguous segment of ones, and `false` otherwise.

Solution Approach

The most efficient solutions leverage the observation that if a '0' is encountered and later a '1' is encountered, it signifies more than one segment of ones. The provided solutions iterate through the string, using a flag or a simple check to detect this condition.

Step-by-Step Algorithm

  1. Step 1: Initialize a flag (e.g., `foundZero`) to `false`. This flag indicates whether a '0' has been encountered.
  2. Step 2: Iterate through the binary string.
  3. Step 3: If a '0' is encountered, set the `foundZero` flag to `true`.
  4. Step 4: If a '1' is encountered and the `foundZero` flag is already `true`, it means there's more than one segment of ones. Return `false`.
  5. Step 5: If the loop completes without finding a '0' followed by a '1', return `true` (at most one segment of ones).

Key Insights

  • Insight 1: The problem can be efficiently solved by iterating through the string only once, keeping track of whether a segment of ones has ended.
  • Insight 2: The presence of a '0' followed by a '1' indicates more than one segment of ones. This is a simple condition to check.
  • Insight 3: The constraint that the string starts with '1' simplifies the problem, eliminating the need for special handling of leading zeros.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: String.

Companies

Asked at: Cisco.