Program to find length of longest substring which contains k distinct characters in Python


Suppose we have a number k and another string s, we have to find the size of the longest substring that contains at most k distinct characters.

So, if the input is like k = 3 s = "kolkata", then the output will be 4, as there are two longest substrings with 3 distinct characters these are "kolk" and "kata", which have length 4.

To solve this, we will follow these steps −

  • ans := 0, left := 0

  • table := a new map

  • for right is in range 0 to size of s − 1, do

    • table[s[right]] := 1 + (s[right] if exists otherwise 0)

    • if size of table <= k, then

      • ans := maximum of ans and (right − left + 1)

    • otherwise,

      • while size of table > k, do

        • left_char := s[left]

        • if table[left_char] is same as 1, then

          • delete left_char−th element from table

        • otherwise,

          • table[left_char] := table[left_char] − 1

        • left := left + 1

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, k, s):
      ans = 0
      left = 0
      table = {}
      for right in range(0, len(s)):
         table[s[right]] = table.get(s[right], 0) + 1
         if len(table) <= k:
            ans = max(ans, right − left + 1)
         else:
            while len(table) > k:
               left_char = s[left]
               if table[left_char] == 1:
                  table.pop(left_char)
               else:
                  table[left_char] −= 1
               left += 1
      return ans
ob = Solution()
k = 3
s = "kolkata"
print(ob.solve(k, s))

Input

"anewcoffeepot"

Output

4

Updated on: 15-Dec-2020

515 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements