#3258

Count Substrings That Satisfy K-Constraint I

Easy
StringSliding WindowSliding 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 the sliding window technique to efficiently count valid substrings without generating all of them. This method maintains a window of characters and adjusts its size based on the counts of '0's and '1's.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize two pointers (left and right) to represent the current window.
  2. 2Step 2: Expand the right pointer to include more characters until the window violates the k-constraint.
  3. 3Step 3: For each valid window, count all possible substrings that can be formed with the current left pointer.
  4. 4Step 4: Move the left pointer to shrink the window until it satisfies the k-constraint again.
  5. 5Step 5: Repeat until the right pointer reaches the end of the string.
solution.py17 lines
1def count_substrings(s, k):
2    left = 0
3    count = 0
4    zeros = ones = 0
5    for right in range(len(s)):
6        if s[right] == '0':
7            zeros += 1
8        else:
9            ones += 1
10        while zeros > k and ones > k:
11            if s[left] == '0':
12                zeros -= 1
13            else:
14                ones -= 1
15            left += 1
16        count += right - left + 1
17    return count

Complexity note: The time complexity is O(n) because each character is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(1) since we are using a fixed amount of extra space.

  • 1The sliding window technique is powerful for problems involving contiguous subarrays or substrings.
  • 2Understanding how to maintain counts of elements while adjusting window boundaries is crucial.

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