#1784
Check if Binary String Has at Most One Segment of Ones
EasyStringTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution involves a single pass through the string to count the segments of '1's. This is efficient because we only need to check transitions from '0' to '1'.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a counter for segments of '1's.
- 2Step 2: Traverse the string character by character.
- 3Step 3: Increment the counter when a '1' is found that follows a '0' or is the first character.
- 4Step 4: If the counter exceeds 1 at any point, return false.
- 5Step 5: If the loop completes and the counter is 1 or less, return true.
solution.py8 lines
1def checkOnesSegment(s):
2 count = 0
3 for i in range(len(s)):
4 if s[i] == '1' and (i == 0 or s[i-1] == '0'):
5 count += 1
6 if count > 1:
7 return False
8 return Trueℹ
Complexity note: The complexity is O(n) because we only make a single pass through the string, checking each character once.
- 1A segment of '1's is defined by transitions from '0' to '1'.
- 2The problem can be solved efficiently by counting these transitions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.