Check if characters of one string can be swapped to form other | Python3 program to check if characters of one string can be swapped to form other ; if length is not same print no ; Count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; Since lengths are same , some value would definitely become negative if result is false . ; Driver Code
MAX = 26 NEW_LINE def targetstring ( str1 , str2 ) : NEW_LINE INDENT l1 = len ( str1 ) NEW_LINE l2 = len ( str2 ) NEW_LINE if ( l1 != l2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT map = [ 0 ] * MAX NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT map [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT map [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE if ( map [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE str2 = " geegeeksksfor " NEW_LINE if ( targetstring ( str1 , str2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT