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
🏛️ Military Formation AnalysisFormation: "1 0 1 1 0" (Soldiers=3, Empty=2)SESSE📊 Tactical AnalysisSoldiers (1s): 3Empty Positions (0s): 2Dominance Test: 3 ≥ 2² = 4❌ NOT Dominant⚡ Algorithm Steps1. For each start position i2. Extend formation, update counts3. Check: soldiers ≥ empty²4. Early stop if impossible⏱️ Performance MetricsTime Complexity: O(n²) - Check all formations efficientlySpace Complexity: O(1) - Only need running counters
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

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for running counters

n
2n
Linear Space

Constraints

  • 1 ≤ s.length ≤ 4 × 104
  • s[i] is either '0' or '1'
  • String contains only binary characters
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
12.4K Views
Medium Frequency
~15 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen