Syntax error Check if characters of one string can be swapped to form other in Python

Check if characters of one string can be swapped to form other in Python



Suppose we have two strings s and t, we have to check whether we can generate t by swapping the character of the s.

So, if the input is like s = "worldlloeh" t = "helloworld", then the output will be True as we can swap characters from "worldlloeh" to make "helloworld".

To solve this, we will follow these steps −

  • s_len := size of s, t_len := size of t
  • if s_len is not same as t_len, then
    • return False
  • freq := a map to store all characters and their frequencies in s
  • for i in range 0 to t_len, do
    • freq[t[i]] := freq[t[i]] - 1
    • if freq[t[i]] < 0, then
      • 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):
   s_len = len(s)
   t_len = len(t)
   if (s_len != t_len):
      return False
   freq = defaultdict(int)
   for char in s :
      freq[char] += 1
   for i in range(t_len) :
      freq[t[i]] -= 1
      if freq[t[i]] < 0:
         return False
   return True
s = "worldlloeh"
t = "helloworld"
print(solve(s, t))

Input

"worldlloeh", "helloworld"

Output

True
Updated on: 2020-12-30T13:43:28+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements