Your code doesn't even return a correct value. This one-liner is O(n log n):
return sorted(word1) == sorted(word2)
For an O(n) solution, you can count all characters:
from collections import Counter
# ...
def check(a, b)
return Counter(a) == Counter(b)
Without collections it is much longer:
def check(a, b):
chars = dict.fromkeys(a + b, 0)
for c in a:
chars[c] += 1
for c in b:
chars[c] -= 1
return not any(chars.values())
This code does the following:
chars = dict.fromkeys(a + b, 0)
: Creates a dict, which has all the occurring characters in either word as keys set to 0.
for c in a: chars[c] += 1
: this will iterate over a
and count the occurrences of each character in it. chars
now contains the count of separate characters, (and some zeroes for characters in b but not a)
for c in b: chars[c] -= 1
: much the same as before, but instead this will subtract the character counts of b
from chars
return not any(chars.values())
: chars['h'] == 0
if and only if a
and b
has the same amount of 'h'
. This line checks if chars
has only zeroes as values, meaning that all characters have the same count in both inputs. (as any
returns if there is any truthy value in the sequence. 0 is falsy, every other integer is truthy.)
Both lists get iterated over once. Assuming O(1) access time for dictionaries makes the whole algorithm run in O(n) time (where n is the total length of the inputs). Space complexity is O(n) too (all characters can be distinct). Don't make that mistake when they ask you complexity. It's not necessary time complexity.