Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on core interview patterns fundamentals.
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 <= 100s[i] is either '0' or '1'.s[0] is '1'.Problem summary: Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"1001"
"110"
longer-contiguous-segments-of-ones-than-zeros)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1784: Check if Binary String Has at Most One Segment of Ones
class Solution {
public boolean checkOnesSegment(String s) {
return !s.contains("01");
}
}
// Accepted solution for LeetCode #1784: Check if Binary String Has at Most One Segment of Ones
func checkOnesSegment(s string) bool {
return !strings.Contains(s, "01")
}
# Accepted solution for LeetCode #1784: Check if Binary String Has at Most One Segment of Ones
class Solution:
def checkOnesSegment(self, s: str) -> bool:
return '01' not in s
// Accepted solution for LeetCode #1784: Check if Binary String Has at Most One Segment of Ones
impl Solution {
pub fn check_ones_segment(s: String) -> bool {
!s.contains("01")
}
}
// Accepted solution for LeetCode #1784: Check if Binary String Has at Most One Segment of Ones
function checkOnesSegment(s: string): boolean {
let pre = s[0];
for (const c of s) {
if (pre !== c && c === '1') {
return false;
}
pre = c;
}
return true;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.