DEV Community

Manasi Patil
Manasi Patil

Posted on

Day 98 of 100 days dsa coding challenge

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)