#3261

Count Substrings That Satisfy K-Constraint II

Hard
ArrayStringBinary SearchSliding WindowPrefix SumSliding WindowTwo PointersPrefix Sum
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 solution uses a sliding window approach to efficiently count valid substrings by maintaining a window of characters that satisfy the k-constraint. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a function to count valid substrings within a given range using a sliding window.
  2. 2Step 2: For each query, determine the left and right bounds of the substring.
  3. 3Step 3: Use two pointers to expand the window and count the number of valid substrings.
  4. 4Step 4: Store results for each query and return them.
solution.py33 lines
1# Full working Python code
2
3def count_valid_substrings(s, k, l, r):
4    count = 0
5    left = 0
6    zeros = 0
7    ones = 0
8    for right in range(l, r + 1):
9        if s[right] == '0':
10            zeros += 1
11        else:
12            ones += 1
13        while zeros > k and ones > k:
14            if s[left] == '0':
15                zeros -= 1
16            else:
17                ones -= 1
18            left += 1
19        count += right - left + 1
20    return count
21
22
23def count_substrings(s, k, queries):
24    results = []
25    for l, r in queries:
26        results.append(count_valid_substrings(s, k, l, r))
27    return results
28
29# Example usage
30s = '0001111'
31k = 2
32queries = [[0, 6]]
33print(count_substrings(s, k, queries))

Complexity note: This complexity is achieved because we only traverse the string once for each query, maintaining a sliding window, leading to linear time complexity.

  • 1Sliding window technique allows us to efficiently count valid substrings without generating all possible substrings.
  • 2Understanding the constraints helps in optimizing the solution by focusing on the counts of '0's and '1's.

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