Solving Leetcode Interviews in Seconds with AI: Check if Binary String Has at Most One Segment of Ones
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1784" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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'.
Explanation
Here's a breakdown of the solution:
- Identify the Transition: The core idea is to find the first occurrence of '0' after a sequence of '1's. If no '0' exists, the string satisfies the condition.
- Check for Subsequent Ones: After the first '0' is encountered, we iterate through the rest of the string. If any '1' is found after this point, it means the ones are not contiguous, and we return
False. Contiguous Ones: If we reach the end of the string without finding any '1' after the initial sequence of ones and zeros, we return
True.Runtime Complexity: O(n), where n is the length of the string.
- Storage Complexity: O(1)
Code
def check_contiguous_ones(s: str) -> bool:
"""
Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones.
Otherwise, return false.
"""
n = len(s)
first_zero_index = -1
# Find the first occurrence of '0'
for i in range(n):
if s[i] == '0':
first_zero_index = i
break
# If no '0' is found, the string contains only '1's, which is a contiguous segment.
if first_zero_index == -1:
return True
# Check if any '1's appear after the first '0'
for i in range(first_zero_index, n):
if s[i] == '1':
return False
return True