Count the Number of Substrings With Dominant Ones - Problem

You are given a binary string s. Return the number of substrings with dominant ones.

A string has dominant ones if the number of ones in the string is greater than or equal to the square of the number of zeros in the string.

In mathematical terms, for a substring with ones count of 1s and zeros count of 0s: ones ≥ zeros²

Input & Output

Example 1 — Basic Case
$ Input: s = "00011"
Output: 5
💡 Note: Valid substrings: "1" (ones=1 ≥ zeros²=0), "11" (ones=2 ≥ zeros²=0), "1" (ones=1 ≥ zeros²=0), "01" (ones=1 ≥ zeros²=1), "011" (ones=2 ≥ zeros²=1)
Example 2 — All Ones
$ Input: s = "101101"
Output: 15
💡 Note: Most substrings work since zeros are limited: single 1s, pairs like "10", "01", and longer valid combinations
Example 3 — Many Zeros
$ Input: s = "1000"
Output: 2
💡 Note: Valid substrings: "1" at start (ones=1 ≥ zeros²=0), and "10" (ones=1 ≥ zeros²=1). Other substrings have too many zeros: "100" needs 1≥4 (fail), "1000" needs 1≥9 (fail)

Constraints

  • 1 ≤ s.length ≤ 4 × 104
  • s consists only of characters '0' and '1'

Visualization

Tap to expand
Count Substrings With Dominant Ones INPUT Binary String s = "00011" 0 i=0 0 i=1 0 i=2 1 i=3 1 i=4 Dominant Condition: ones >= zeros^2 Zero positions: [0, 1, 2] One positions: [3, 4] Length n = 5 Total substrings = 15 ALGORITHM STEPS 1 Group by Zero Count Track zero positions in string 2 Enumerate Zero Counts For k zeros: need ones >= k^2 3 Calculate Valid Ranges Find start/end for each group 4 Count Valid Substrings Sum all dominant substrings Valid Substrings Analysis k=0: "1","1","11" (3) k=1: "011" (1^2=1, ones=2) OK k=1: "0011" (ones=2) OK k=2: need 4 ones (none) k=3: need 9 ones (none) FINAL RESULT Dominant Substrings Found: "1" "1" "11" "011" "0011" Count Breakdown: 0 zeros: 3 substrings 1 zero: 2 substrings OUTPUT 5 OK - 5 dominant substrings Key Insight: Group substrings by their zero count k. For each k, we need at least k^2 ones to be dominant. Since k^2 grows fast, we only need to check small values of k (up to sqrt(n)), making this O(n*sqrt(n)). TutorialsPoint - Count the Number of Substrings With Dominant Ones | Group by Zero Count Approach
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
234 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