Count the Number of Substrings With Dominant Ones - Problem
You are given a binary string s containing only '0' and '1' characters. Your task is to find the number of substrings where the ones are dominant.
A substring has dominant ones if:
- The number of ones ≥ (number of zeros)²
- In mathematical terms:
count_of_ones ≥ count_of_zeros²
Example: In substring "101", we have 2 ones and 1 zero. Since 2 ≥ 1², this substring has dominant ones.
Return the total count of all such substrings in the given binary string.
Input & Output
example_1.py — Basic Case
$
Input:
s = "10110"
›
Output:
9
💡 Note:
Valid substrings: "1"(×3), "10", "101", "1011", "11", "110", "0" (when zeros²=0). Total count is 9 substrings with dominant ones.
example_2.py — All Ones
$
Input:
s = "111"
›
Output:
6
💡 Note:
All possible substrings have dominant ones since there are no zeros: "1"(×3), "11"(×2), "111"(×1). Total: 3+2+1 = 6.
example_3.py — Many Zeros
$
Input:
s = "00011"
›
Output:
5
💡 Note:
Valid substrings are single '1' characters and substrings ending with enough ones: "1"(×2), "01", "001", "011". Total: 5 valid substrings.
Visualization
Tap to expand
Understanding the Visualization
1
Formation Scanning
Examine each possible formation (substring) starting from every position
2
Force Counting
Use running tallies to efficiently track soldiers and empty positions as formation extends
3
Dominance Check
Verify if current soldier count ≥ (empty positions)² for tactical superiority
4
Strategic Termination
Stop extending when mathematical impossibility detected (optimization)
Key Takeaway
🎯 Key Insight: The dominance condition ones ≥ zeros² creates natural bounds that allow early termination optimizations, making the O(n²) solution practical even for larger inputs.
Time & Space Complexity
Time Complexity
O(n²)
O(n²) for generating all substrings, but with O(1) dominance checking per substring due to running counts
⚠ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for running counters
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 4 × 104
- s[i] is either '0' or '1'
- String contains only binary characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code