Program to find the length of longest substring which has two distinct elements in Python


Suppose we have a string s, we have to find the length of the longest substring that contains at most 2 distinct characters.

So, if the input is like s = "xyzzy", then the output will be 4, as "yzzy" is the longest substring with at most 2 unique characters.

To solve this, we will follow these steps−

  • start := 0

  • c := a map

  • ans := 0

  • for end in range 0 to size of s, do

    • c[s[end]] := c[s[end]] + 1

    • while size of c > 2, do

      • c[s[start]] := c[s[start]] - 1


      • if c[s[start]] is 0, then

        • delete c[s[start]]

      • start := start + 1

    • ans := maximum of ans and (end - start + 1)

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      from collections import Counter
      start = 0
      c = Counter()
      ans = 0
      for end in range(len(s)):
         c[s[end]] += 1
         while len(c) > 2:
            c[s[start]] -= 1
            if not c[s[start]]:
               del c[s[start]]
            start += 1
         ans = max(ans, end - start + 1)
      return ans
ob = Solution()
s = "xyzzy"
print(ob.solve(s))

Input

s = "xyzzy"

Output

4

Updated on: 10-Oct-2020

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements