The code written in Python 3.6 mostly using Python's built in functions sorted and len
. First I'm checking for the edge case that the two given strings are not of the same length obviously. Then I'm sorting the strings and comparing if their sorted value are equal to each other with a boolean expression. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Just for the sake of practising Big-O this function runs in \$O(1)\$ constant complexity time because regardless of the strings given the function will always return a Boolean value. Is this correct? I realized my assumption was not correct since the function will run in the time complexity of the sorted built-in function which is \$nlog(n)\$.
If you were an interviewer would you prefer the candidate to not use Python's built in functions and to resort to a more manual way of solving the problem?
def is_anagram(string1, string2):
while len(string1) == len(string2):
# Testing sorted values equality
if sorted(string1) == sorted(string2):
return True
return False
return 'The strings are not anagrams they have differing lengths'
print(is_anagram('cat', 'cra'))