You are given two words, s and t, made of lower-case letters. t is an anagram of s when it uses exactly the same letters, each one the same number of times, only rearranged.
Answer true when the two words are anagrams of each other, and false otherwise.
Example 1
Input: s = "stop", t = "pots" Output: true Why: both use one each of s, t, o and p
2 more examples and the constraints
Example 2
Input: s = "seed", t = "sped" Output: false Why: s has two e's and no p; t has one e and a p
Example 3
Input: s = "ab", t = "abb" Output: false Why: different lengths can never match
Constraints
- 1 ≤ length of s, length of t ≤ 50,000
- Both strings hold only the letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort both stringsO(n log n)
- Count the lettersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 letters | Verdict |
|---|---|---|---|
| Sort both strings | O(n log n) | Passes; simplest to write | |
| Count the letters | O(n) | Best; one pass over each |
n = length of the strings.
Edge cases to test
- Different lengths. "ab" and "abb" can never be anagrams; check this first.
- Same letters, different counts. "aab" and "abb" share the letters a and b but not their counts.
- Identical strings. A word is an anagram of itself: "loop" and "loop" give true.
- One letter. "a" and "a" is true, "a" and "b" is false.
Common mistakes
- Checking only that each letter of
tappears ins, which says "aab" and "abb" match. - Forgetting the length check, so a
tthat is a shorter piece ofspasses. - Using a 26-slot array and then being asked about Unicode, with no plan for it.
How to talk through it
- 1Clarify. Only lower-case a to z? Can the lengths differ? What about Unicode?
- 2Give the simple version. Sort both and compare: O(n log n), and easy to trust.
- 3Name what really matters. An anagram is the same count for every letter. Counting is O(n).
- 4Code the count. Add for
s, subtract fort, and fail the moment a count would go below 0. - 5Test out loud. Run "aab" against "abb" and a pair of different lengths before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?