HardNo. 2953
Count Complete Substrings — LeetCode 2953 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, 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
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
- Time
- O(n × |Σ|)
- Space · auxiliary
- O(|Σ|), where n is the length of the string word; and Σ is the size of the character set
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
| No. | Problem | Difficulty |
|---|---|---|
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0424 | Longest Repeating Character Replacement | Medium |
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 × |Σ|).
- What is the space complexity of LeetCode 2953. Count Complete Substrings?
The Python solution on this page uses O(|Σ|), 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.