#3234

Count the Number of Substrings With Dominant Ones

Medium
StringEnumerationSliding WindowTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a sliding window technique to efficiently count dominant substrings by maintaining a count of zeros and ones as we expand the window. This avoids the need to re-count for every substring.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a count for dominant substrings and a hashmap to store the count of zeros.
  2. 2Step 2: Use two pointers to represent the current window of the substring.
  3. 3Step 3: Expand the right pointer and update the counts of zeros and ones.
  4. 4Step 4: If the substring is not dominant, move the left pointer to shrink the window until it becomes dominant again.
  5. 5Step 5: Count all valid substrings ending at the right pointer.
solution.py24 lines
1# Full working Python code
2
3def countDominantSubstrings(s):
4    count = 0
5    left = 0
6    ones = 0
7    zeros = 0
8    n = len(s)
9    for right in range(n):
10        if s[right] == '1':
11            ones += 1
12        else:
13            zeros += 1
14        while ones < zeros * zeros:
15            if s[left] == '1':
16                ones -= 1
17            else:
18                zeros -= 1
19            left += 1
20        count += right - left + 1
21    return count
22
23# Example usage
24print(countDominantSubstrings('00011'))  # Output: 5

Complexity note: The time complexity is O(n) because we traverse the string with two pointers, ensuring each character is processed at most twice.

  • 1Understanding the condition for dominant ones is crucial for substring evaluation.
  • 2Using a sliding window approach can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.