Count Complete Substrings — LeetCode 2953 Python Solution
HardHash TableStringSliding Window
- Problem
- #2953
- Pattern
- Sliding Window
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You are given a string word and an integer k. A substring s of word is complete if: Each character in s occurs exactly k times.
Example
- Input
- word = "igigee", k = 2
- Output
- 3
- Explanation
- The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: igigee, igigee, igigee.
Python solution
Python
class Solution:
def countCompleteSubstrings(self, word: str, k: int) -> int:
def f(s: str) -> int:
m = len(s)
ans = 0
for i in range(1, 27):
l = i * k
if l > m:
break
cnt = Counter(s[:l])
freq = Counter(cnt.values())
ans += freq[k] == i
for j in range(l, m):
freq[cnt[s[j]]] -= 1
cnt[s[j]] += 1
freq[cnt[s[j]]] += 1
freq[cnt[s[j - l]]] -= 1
cnt[s[j - l]] -= 1
freq[cnt[s[j - l]]] += 1
ans += freq[k] == i
return ans
n = len(word)
ans = i = 0
while i < n:
j = i + 1
while j < n and abs(ord(word[j]) - ord(word[j - 1])) <= 2:
j += 1
ans += f(word[i:j])
i = j
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times |\Sigma|) |
| Space | O(|\Sigma|), where n is the length of the string word; and \Sigma is the size of the character set auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2953. Count Complete Substrings is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHardLeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 424Longest Repeating Character ReplacementMedium
Frequently asked questions
- How hard is LeetCode 2953. Count Complete Substrings?
- LeetCode 2953. Count Complete Substrings is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2953. Count Complete Substrings?
- The Python solution on this page runs in O(n \times |\Sigma|).
- What is the space complexity of LeetCode 2953. Count Complete Substrings?
- The Python solution on this page uses O(|\Sigma|), where n is the length of the string word; and \Sigma is the size of the character set auxiliary space.
- What topics does LeetCode 2953. Count Complete Substrings cover?
- LeetCode 2953. Count Complete Substrings is tagged Hash Table, String and Sliding Window on LeetCode.