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 −
Let us see the following implementation to get better understanding −
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))