Longer Contiguous Segments of Ones than Zeros Problem
#1869
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1869.
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.
- For example, in
s = "110100010"the longest continuous segment of1s has length2, and the longest continuous segment of0s has length3.
Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
Example 1:
Input: s = "1101"
Output: true
Explanation:
The longest contiguous segment of 1s has length 2: "1101"
The longest contiguous segment of 0s has length 1: "1101"
The segment of 1s is longer, so return true.
Example 2:
Input: s = "111000"
Output: false
Explanation:
The longest contiguous segment of 1s has length 3: "111000"
The longest contiguous segment of 0s has length 3: "111000"
The segment of 1s is not longer, so return false.
Example 3:
Input: s = "110100010"
Output: false
Explanation:
The longest contiguous segment of 1s has length 2: "110100010"
The longest contiguous segment of 0s has length 3: "110100010"
The segment of 1s is not longer, so return false.
Constraints:
1 <= s.length <= 100s[i]is either'0'or'1'.
Solution
Approach: Longest Run of Each Character
Write a helper that returns the length of the longest run of a given character in s. The answer is true exactly when the longest run of 1 is strictly longer than the longest run of 0. One scan can compute both.
Complexity: O(n) time and O(1) space.
class Solution:
def checkZeroOnes(self, s: str) -> bool:
def f(x: str) -> int:
cnt = mx = 0
for c in s:
if c == x:
cnt += 1
mx = max(mx, cnt)
else:
cnt = 0
return mx
return f("1") > f("0")