For both strings, generate a dictionary containing distinct characters of the string as keys and their respective counts as values.
If the two dictionaries are equal, the strings are permutations of each other.
Instead of manually counting characters using a dict
, you can utilize the collections.Counter
class:. To save time in case the strings are of different length, you can compare their lengths first.
from collections import Counter
def checkPermutation(str1, str2):
return len(str1) == len(str2) and Counter(str1) == Counter(str2)
This is a \$O(n)\$ time and approximately \$O(1)\$ space solution. Approximately because – presumably – the less distinct characters there are in the input strings, the less space is occupied by the counters.