The Count the Number of Substrings With Dominant Ones interview question involves a binary string. A substring is considered to have "dominant ones" if the count of '1's in it is at least the square of the count of '0's in it (count1≥count02).
You need to find the total number of such substrings.
Why is this asked in interviews?
This "Medium" problem is used by Meta, Amazon, and Google to test optimization of the sliding window interview pattern or enumeration. The key insight is that since count1≤N, and count1≥count02, the number of zeros in a valid substring is bounded by N. This allows you to iterate over the number of zeros rather than the substring boundaries.
Algorithmic pattern used
The problem uses Enumeration by Zeros.
Record the indices of all '0's in the string.
Iterate through each index i as the start of a substring.
For each i, iterate through the upcoming '0's. Since count0≤N, you only check about ∼200 zeros even for N=40,000.
For each number of zeros Z, find the range of indices [L,R] that contain exactly Z zeros.
In this range, calculate how many '1's exist and check the condition count1≥Z2.
Sum the counts.
Example explanation
s = "1011", count1≥count02
Start at i=0:
0 zeros: "1", "1...". Max 1s is 1. 1≥02. (Valid).
1 zero: "10", "101", "1011". count0=1, so need count1≥12=1.
"10": 1 one (Valid).
"101": 2 ones (Valid).
"1011": 3 ones (Valid).
Start at i=1... and so on.
Common mistakes candidates make
Brute force:O(N2) will be too slow if N=40,000.
Off-by-one: Incorrectly identifying the range of indices between zeros.
Ignoring the square: Getting the condition count1≥count0 mixed up with count1≥count02.
Interview preparation tip
Whenever a problem involves a constraint like X≥Y2, check the bounds of Y. If X is bounded by N, then Y is bounded by N. Reducing a search space from N to N is a common "Medium to Hard" optimization trick.