LeetCode solutions

3543. Count Substrings That Satisfy K-Constraint I

My accepted Python solution to LeetCode problem 3543, Count Substrings That Satisfy K-Constraint I, running in 19ms.

  • Difficulty: Easy
  • Python
  • Runtime 19ms
  • Memory 17.5MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 19ms, memory 17.5MB, accepted 2025-12-31.

python
class Solution:
    def countKConstraintSubstrings(self, s: str, k: int) -> int:
        n = len(s)
        count = 0
        for i in range(n):
            zeros = 0
            ones = 0
            for j in range(i, n):
                if s[j] == '0':
                    zeros += 1
                else:
                    ones += 1
                if zeros <= k or ones <= k:
                    count += 1
                else:
                    break
        return count

Source