To optimize the count_one_prominent_substrings method, we can significantly reduce its time complexity from ( O(n^2) ) to ( O(n \sqrt{n}) ). The original method enumerates all possible substrings and checks the condition ( \text{count}_0^2 \leq \text{count}_1 ) for each, which is computationally expensive for large strings.
Optimization Strategy
-
Limit the Number of '0's (( k )):
- The condition ( \text{count}_0^2 \leq \text{count}_1 ) implies that for a substring with ( k ) '0's, it must contain at least ( k^2 ) '1's.
- Given the total length of the string ( n ), the maximum number of '0's (( k_{\text{max}} )) in any valid substring is ( \lfloor \sqrt{n} \rfloor ). Beyond this, ( k^2 > n ), making the condition impossible to satisfy.
-
Precompute Positions of '0's:
- Store the indices of all '0's in the string. This allows us to efficiently iterate over substrings containing a specific number of '0's.
-
Iterate Over Possible Counts of '0's:
- For each possible ( k ) from 0 to ( k_{\text{max}} ), count all substrings that contain exactly ( k ) '0's and satisfy ( \text{count}_1 \geq k^2 ).
-
Use Prefix Sums:
- Precompute prefix sums for both '0's and '1's to quickly calculate the number of '0's and '1's in any substring.
-
Efficient Counting for Each ( k ):
- For each window of exactly ( k ) '0's, determine the range of possible starting and ending indices.
- Instead of iterating one step at a time for both the start and end, leverage the precomputed prefix sums and the limited range of ( k ) to minimize computations.
Optimized Implementation
Here's the optimized Python implementation based on the above strategy:
def count_one_prominent_substrings(s):
n = len(s)
# Precompute prefix sums for '0's and '1's
prefix_1 = [0] * (n + 1)
prefix_0 = [0] * (n + 1)
for i in range(n):
prefix_1[i + 1] = prefix_1[i] + (s[i] == '1')
prefix_0[i + 1] = prefix_0[i] + (s[i] == '0')
count = 0
k_max = int(n**0.5) + 1 # Maximum number of '0's to consider
# Get all positions of '0's
zero_positions = [i for i, c in enumerate(s) if c == '0']
m = len(zero_positions)
for k in range(0, k_max + 1):
if k > m:
break # No substrings with more '0's than exist in the string
if k == 0:
# Count all substrings consisting solely of '1's
L = 0
for c in s:
if c == '1':
L += 1
else:
count += L * (L + 1) // 2
L = 0
count += L * (L + 1) // 2 # Add the last run of '1's
else:
# Iterate over all possible windows with exactly k '0's
for i in range(m - k + 1):
first_zero = zero_positions[i]
last_zero = zero_positions[i + k - 1]
# Determine the possible start positions
if i == 0:
left = 0
else:
left = zero_positions[i - 1] + 1
# Determine the possible end positions
if i + k < m:
right = zero_positions[i + k] - 1
else:
right = n - 1
# Iterate over all valid start and end positions within the window
# This is where the optimization happens by limiting the range
for start in range(left, first_zero + 1):
# Binary search to find the minimum end where c1 >= k^2
low = last_zero
high = right
valid_end = right + 1 # Initialize beyond the right boundary
while low <= high:
mid = (low + high) // 2
c1 = prefix_1[mid + 1] - prefix_1[start]
if c1 >= k ** 2:
valid_end = mid
high = mid - 1
else:
low = mid + 1
# All ends from valid_end to right satisfy the condition
if valid_end <= right:
count += (right - valid_end + 1)
return count
Explanation of Optimizations
-
Limiting ( k ) to ( \sqrt{n} ):
- By restricting ( k ) to ( k_{\text{max}} = \lfloor \sqrt{n} \rfloor ), we ensure that the number of iterations remains manageable, especially for large ( n ).
-
Binary Search for Valid Ends:
- For each valid start position within a window of exactly ( k ) '0's, perform a binary search to find the smallest end index where the number of '1's (( c1 )) meets or exceeds ( k^2 ).
- Once this end index is found, all subsequent end indices within the window will also satisfy ( c1 \geq k^2 ), allowing us to add them in bulk without further individual checks.
-
Efficient Counting of All-'1's Substrings:
- For ( k = 0 ), instead of iterating through all possible substrings of '1's, we compute the number of such substrings based on the lengths of consecutive '1's runs. This avoids the inner loop entirely for this case.
Time Complexity Analysis
Practical Considerations
-
Binary Search:
- Implementing the binary search for each start position helps reduce the number of iterations needed to find valid end positions, especially when the number of '1's required is large.
-
Space Complexity:
- The space used by prefix sums and zero positions is linear in terms of ( n ), i.e., ( O(n) ).
Example Usage
# Example string
s = "110100110"
# Count the number of one-prominent substrings
result = count_one_prominent_substrings(s)
print(result) # Output will depend on the string
This optimized approach should perform significantly better on larger strings by reducing unnecessary iterations and leveraging efficient search techniques.