#1869
Longer Contiguous Segments of Ones than Zeros
EasyStringTwo PointersSliding WindowCounting Segments
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)
We can traverse the string once while counting the lengths of contiguous segments of 1s and 0s. This approach is efficient because it only requires a single pass through the string.
⚙️
Algorithm
5 steps- 1Step 1: Initialize variables to track the maximum lengths of contiguous 1s and 0s.
- 2Step 2: Use a single loop to iterate through the string, counting the length of the current segment.
- 3Step 3: When the character changes, update the maximum length for the previous character.
- 4Step 4: At the end of the loop, ensure to check the last segment.
- 5Step 5: Compare the maximum lengths of 1s and 0s and return the result.
solution.py17 lines
1def checkZeroOnes(s):
2 max_ones = max_zeros = 0
3 current_count = 1
4 for i in range(1, len(s)):
5 if s[i] == s[i - 1]:
6 current_count += 1
7 else:
8 if s[i - 1] == '1':
9 max_ones = max(max_ones, current_count)
10 else:
11 max_zeros = max(max_zeros, current_count)
12 current_count = 1
13 if s[-1] == '1':
14 max_ones = max(max_ones, current_count)
15 else:
16 max_zeros = max(max_zeros, current_count)
17 return max_ones > max_zerosℹ
Complexity note: The time complexity is O(n) because we only traverse the string once, counting segments as we go. The space complexity is O(1) since we are using a constant amount of space for our variables.
- 1The longest contiguous segment of 1s or 0s can be found by counting as we traverse the string.
- 2A single pass through the string is sufficient to determine the maximum lengths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.