Check if Two Strings are Anagrams
Table of Contents + β
This one looks simple. But the interviewer is watching how you think. They want to see if you jump straight to sorting. Or if you spot the faster trick. So let us walk through both. The way you would actually say it out loud in the room.
π€ The Problem
You get two strings. You have to tell if they are anagrams. Anagram means one string is just a rearrangement of the other. Same letters. Same count of each letter. Only the order is different.
Think of the word βlistenβ and the word βsilentβ. Same six letters. Just shuffled around. So they are anagrams.
Input: s = "listen", t = "silent"Output: true
Input: s = "hello", t = "world"Output: falseOne quick check first. If the two strings have different lengths, they can never be anagrams. So you return false right away.
π’ The Brute Way: Sort Both
The first idea most people say is sorting. Sort the letters of both strings. If they are anagrams, the sorted versions become exactly the same string.
So βlistenβ sorted becomes βeilnstβ. And βsilentβ sorted also becomes βeilnstβ. They match. So the answer is true.
This works. But sorting costs time. Sorting a string of length n takes about O(n log n). That is fine. But we can do better. The interviewer almost always wants the faster one next.
π The Optimal Way: Count the Letters
Here is the smarter idea. We do not need the letters in order. We only need to know how many times each letter appears.
So we keep a small count for every letter. For lowercase English letters there are only 26 of them. So a simple array of size 26 is enough.
The trick is one single pass. While we walk through both strings together, we add one for each letter in the first string and subtract one for each letter in the second string. If the strings are true anagrams, every letter we added also got subtracted. So at the end every count is zero.
If even one count is not zero, the letters did not match up. So they are not anagrams.
Steps to check anagrams by counting:
- If the two lengths are different, return false.
- Make a count array of size 26, all set to zero.
- Walk through both strings together. Add one for the letter from the first string. Subtract one for the letter from the second string.
- Go through the count array. If any value is not zero, return false.
- If every value is zero, return true.
def is_anagram(s, t): # Different lengths can never be anagrams if len(s) != len(t): return False
count = [0] * 26 for i in range(len(s)): count[ord(s[i]) - ord('a')] += 1 # add for first string count[ord(t[i]) - ord('a')] -= 1 # subtract for second string
# If every count is zero, the letters matched up return all(c == 0 for c in count)
print(is_anagram("listen", "silent"))print(is_anagram("hello", "world"))The output of the above code will be:
TrueFalseβ±οΈ Time and Space Complexity
The counting way wins because it touches each letter only once. Sorting has to rearrange everything first. So sorting at O(n log n) is slower.
| Approach | Time | Space |
|---|---|---|
| Sort both strings | O(n log n) | O(1) or O(n) |
| Count letters (optimal) | O(n) | O(1) |
The count array is always size 26, no matter how long the strings are. So we call that space O(1). It does not grow with the input.
Tip
If the interviewer says the strings can have any character, not just lowercase a to z, do not use a size 26 array. Use a hash map instead. The key is the character and the value is its count. The same add-and-subtract idea still works.
π§© Key Takeaways
- β Anagrams have the same letters with the same count. Only the order changes.
- β First check the lengths. Different length means not an anagram, and you stop early.
- β Sorting both strings works but costs O(n log n) time.
- β Counting letters in one pass is the optimal way at O(n) time and O(1) space.
- β For letters beyond a to z, swap the size 26 array for a hash map.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does it mean for two strings to be anagrams?
Why: Anagrams use the same letters the same number of times, only the order differs.
- 2
Why do we check the lengths of the two strings first?
Why: If the strings differ in length they cannot have the same letter counts, so we return false right away.
- 3
What is the time complexity of the optimal counting approach?
Why: We walk through the strings once, so the work grows linearly with the length n.
- 4
Why is the count array considered O(1) space?
Why: The array stays a fixed size of 26 no matter how long the strings are, so the extra space is constant.