Interview Q&A / Python

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Write a function to check whether two strings are anagrams of each other.

SHORT ANSWER

Two strings are anagrams if they contain the same characters with the same counts. Compare Counter(a) with Counter(b) in O(n) time, or compare sorted(a) with sorted(b) in O(n log n) time.

Explain it simply

"listen" and "silent" use the same letters, just in a different order. So order does not matter; counts do.

Line by line

python
from collections import Counter

def is_anagram(a, b):
    a = a.replace(" ", "").lower()
    b = b.replace(" ", "").lower()
    return Counter(a) == Counter(b)

def is_anagram_sorted(a, b):
    return sorted(a.lower()) == sorted(b.lower())

print(is_anagram("listen", "silent"))        # Output: True
print(is_anagram("Dormitory", "dirty room")) # Output: True
print(is_anagram("abc", "abd"))              # Output: False
print(is_anagram_sorted("aab", "abb"))       # Output: False

Counter builds a dictionary of letter counts, and two Counters compare equal when all counts match. The sorted version is shorter but does more work for long strings.

Complexity

Counter version: time O(n), space O(k) where k is the number of distinct characters. Sorted version: time O(n log n), space O(n).

What to say in the interview

"First check the lengths if spaces aren't ignored, since different lengths can't be anagrams. Then compare character counts with Counter. Sorting both strings also works and is easy to explain, but it is slower asymptotically."

#python#strings#coding

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.