Skip to the solution
EasyDSA14 min read

How do you check if two strings are anagrams?

381 views

The problem

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 False immediately.
  • Two solutions: sorted(s) == sorted(t) in O(n log n), and counting in O(n) with a dict or collections.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 a str returns a list; Python strings are sequences of code points, but visually identical text can still differ (composed vs decomposed accents) without unicodedata.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.

  • strings
  • hashing

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonCounting anagram check on eight inputs, including case and spaces
PythonSorting vs hash-map counting vs 26-slot array: all three agree

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 29 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you check if a binary tree is symmetric?

Continue