Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/count-number-of-substrings4528/1
Substrings with K Distinct
Difficulty: Medium Accuracy: 20.46%
You are given a string s consisting of lowercase characters and an integer k, You have to count all possible substrings that have exactly k distinct characters.
Examples :
Input: s = "abc", k = 2
Output: 2
Explanation: Possible substrings are ["ab", "bc"]
Input: s = "aba", k = 2
Output: 3
Explanation: Possible substrings are ["ab", "ba", "aba"]
Input: s = "aa", k = 1
Output: 3
Explanation: Possible substrings are ["a", "a", "aa"]
Constraints:
1 β€ s.size() β€ 106
1 β€ k β€ 26
Solution:
class Solution:
def countSubstr(self, s, k):
return self.atMost(s, k) - self.atMost(s, k - 1)
def atMost(self, s, k):
if k == 0:
return 0
count = {}
left = 0
res = 0
for right in range(len(s)):
count[s[right]] = count.get(s[right], 0) + 1
while len(count) > k:
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1
res += right - left + 1
return res
Top comments (0)