Question presented to candidate: "Write a Python function that takes two strings and returns whether one is an anagram of the other โ same characters, same number of times, any order. Then tell me its complexity and how you would change it if case and spaces should be ignored."
What a strong answer should cover:
- The definition in terms of counts: anagrams have identical character frequencies, and different lengths mean
Falseimmediately. - Two solutions:
sorted(s) == sorted(t)in O(n log n), and counting in O(n) with adictorcollections.Counter. - Space: O(k) for the counts (k distinct characters), or O(1) with a 26-slot list when input is guaranteed
aโz. - Normalising both strings the same way (
.lower(), removing spaces) when the rules say case and spaces do not count. - Python specifics:
Counter(s) == Counter(t)is the idiomatic one-liner;sorted()on astrreturns a list; Python strings are sequences of code points, but visually identical text can still differ (composed vs decomposed accents) withoutunicodedata.normalize.
Clarifying questions expected:
- Case-sensitive? Do spaces and punctuation count?
- Only lowercase
aโz, or any Unicode?
Code / implementation expected: Yes โ an is_anagram(s, t) function in Python, ideally the O(n) counting version, run on a few true/false cases.