Program to find minimum string size that contains given substring in Python


Suppose we have two strings s and t, we have to find the size of a minimum substring in s that contains all the characters of t. If there is no such substring exists then return -1.

So, if the input is like s = "thegrumpywizardmakes" t = "wake", then the output will be 10, as the shortest substring that contains "wake" is "wizardmake" (length of 10).

To solve this, we will follow these steps −

  • counter := frequency of each character in b

  • start := 0

  • min_subs := inf

  • rem := count of distinct characters in b

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

    • current := a[end]

    • if current is in counter, then

      • counter[current] := counter[current] - 1

      • if counter[current] is same as 0, then

        • rem := rem - 1

    • while rem is same as 0, do

      • prev_char := a[start]

      • if prev_char is in counter, then

        • counter[prev_char] := counter[prev_char] + 1

        • if counter[prev_char] > 0, then

          • rem := rem + 1

      • min_subs := minimum of min_subs and (end - start + 1)

      • start := start + 1

  • return min_subs when min_subs is not inf otherwise -1

Example (Python)

Let us see the following implementation to get better understanding −

class Solution:
   def solve(self, a, b):
      counter = {}
      for char in b:
         counter[char] = counter.get(char, 0) + 1
      start = 0
      min_subs = float("inf")
      rem = len(counter)
      for end in range(len(a)):
         current = a[end]
         if current in counter:
            counter[current] -= 1
            if counter[current] == 0:
               rem -= 1
         while rem == 0:
            prev_char = a[start]
            if prev_char in counter:
               counter[prev_char] += 1
               if counter[prev_char] > 0:
                  rem += 1
               min_subs = min(min_subs, end - start + 1)
               start += 1
      return min_subs if min_subs != float("inf") else -1
ob = Solution()
s = "thegrumpywizardmakes"
t = "wake"
print(ob.solve(s, t))

Input

"thegrumpywizardmakes", "wake"

Output

2

Updated on: 21-Dec-2020

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements