Magicsheet logo

Count the Number of Substrings With Dominant Ones

Medium
25%
Updated 8/1/2025

Count the Number of Substrings With Dominant Ones

What is this problem about?

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 (count1count02count_1 \ge count_0^2).

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 count1Ncount_1 \le N, and count1count02count_1 \ge count_0^2, the number of zeros in a valid substring is bounded by N\sqrt{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.

  1. Record the indices of all '0's in the string.
  2. Iterate through each index i as the start of a substring.
  3. For each i, iterate through the upcoming '0's. Since count0Ncount_0 \le \sqrt{N}, you only check about 200\sim 200 zeros even for N=40,000N=40,000.
  4. For each number of zeros ZZ, find the range of indices [L,R][L, R] that contain exactly ZZ zeros.
  5. In this range, calculate how many '1's exist and check the condition count1Z2count_1 \ge Z^2.
  6. Sum the counts.

Example explanation

s = "1011", count1count02count_1 \ge count_0^2

  1. Start at i=0:
    • 0 zeros: "1", "1...". Max 1s is 1. 1021 \ge 0^2. (Valid).
    • 1 zero: "10", "101", "1011". count0=1count_0=1, so need count112=1count_1 \ge 1^2 = 1.
      • "10": 1 one (Valid).
      • "101": 2 ones (Valid).
      • "1011": 3 ones (Valid).
  2. Start at i=1... and so on.

Common mistakes candidates make

  • Brute force: O(N2)O(N^2) will be too slow if N=40,000N=40,000.
  • Off-by-one: Incorrectly identifying the range of indices between zeros.
  • Ignoring the square: Getting the condition count1count0count_1 \ge count_0 mixed up with count1count02count_1 \ge count_0^2.

Interview preparation tip

Whenever a problem involves a constraint like XY2X \ge Y^2, check the bounds of YY. If XX is bounded by NN, then YY is bounded by N\sqrt{N}. Reducing a search space from NN to N\sqrt{N} is a common "Medium to Hard" optimization trick.

Similar Questions