PPractick

DSA interview question

Valid Anagram

Easy · Algorithms · Topics: string, hash map, sorting

The problem

A word game awards points when a player rearranges all the letters of one word into another, like "listen" → "silent". The validator must decide whether two strings are anagrams: exactly the same letters with exactly the same counts, in any order. Sorting both strings and comparing works in O(n log n), but because the alphabet is small, a frequency count does it in O(n): add one for each letter of the first string, subtract one for each letter of the second, and check that everything cancels out.

Example: ("anagram", "nagaram") → true; ("rat", "car") → false.

Function signature

bool isAnagram(const string& s, const string& t);  // lowercase English letters

Test cases

Input (s, t)OutputExplanation
("anagram", "nagaram")trueSame letters, same counts
("rat", "car")falset has a c, s has a t
("a", "ab")falseDifferent lengths
("", "")true
("aacc", "ccac")falsea appears twice in s but once in t
("listen", "silent")true

(Confirm: lowercase English letters only; a Unicode version would use a hash map instead of an array.)

How interviewers phrase it

Clarifying questions to ask

  1. Which characters: lowercase letters, ASCII, or Unicode?
  2. Case-sensitive? Do spaces count?
  3. How long are the strings?

Follow-ups to expect

  1. "Sorting or counting?"
  2. "How would you handle Unicode?"
  3. "How would you group many words into anagram sets?"
  4. "How do you find anagrams of a pattern inside a long text?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in