Check if a string can be formed from another string using given constraints in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings lowercase strings s and t. We have to check whether t can be generated from s using following constraints or not −

  • Characters of t is there in s for example if there are two 'a' in t, then s should also have two 'a's.

  • When any character in t is not in s, check whether the previous two characters (previous two ASCII values) are there in s or not. For example, if 'f' is in t but not in s, then 'd' and 'e' can be used from s to make 'f'.

So, if the input is like s = "pghn" t = "pin", then the output will be True as we can make 'i' from 'g' and 'h' to make "pin".

To solve this, we will follow these steps −

  • freq := frequency of each character in s
  • for i in range 0 to size of t, do
    • if freq[t[i]] is non-zero, then
      • freq[t[i]] := freq[t[i]] - 1
    • otherwise when freq[first previous character of t[i]] and freq[second previous character of t[i]] is non-zero, then
      • decrease freq[first previous character of t[i]] by 1
      • decrease freq[second previous character of t[i]] by 1
    • otherwise,
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

from collections import defaultdict
def solve(s, t):
   freq = defaultdict(lambda:0)
   for i in range(0, len(s)):
      freq[s[i]] += 1
   for i in range(0, len(t)):
      if freq[t[i]]:
         freq[t[i]] -= 1
      elif (freq[chr(ord(t[i]) - 1)] and freq[chr(ord(t[i]) - 2)]):
         freq[chr(ord(t[i]) - 1)] -= 1
         freq[chr(ord(t[i]) - 2)] -= 1
      else:
         return False
   return True
s = "pghn"
t = "pin"
print(solve(s, t))

Input

"pghn", "pin"

Output

True
raja
Published on 29-Dec-2020 17:36:50
Advertisements