Check whether second string can be formed from characters of first string in Python


Suppose we have two strings s and t. We have to check whether t can be formed using characters of s or not.

So, if the input is like s = "owleh" t = "hello", then the output will be True.

To solve this, we will follow these steps −

  • freq := a map containing all characters and their frequencies
  • for i in range 0 to size of t - 1, do
    • if freq[t[i]] is 0, then
      • return False
    • freq[t[i]] := freq[t[i]] - 1
  • return True

Let us see the following implementation to get better understanding −

Example Code

Live Demo

from collections import defaultdict
 
def solve(s, t):
   freq = defaultdict(int)
 
   for i in range(len(s)):
      freq[s[i]] += 1
     
   for i in range(len(t)):
      if freq[t[i]] == 0:
         return False
      freq[t[i]] -= 1
   return True

s = "owhtlleh"
t = "hello"
print(solve(s, t))

Input

"apuuppa"

Output

True

Updated on: 16-Jan-2021

382 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements