Valid anagram
EasyStuck?
Show a hintHide the hint
Count each letter in both words and compare the counts. Sorting both and comparing also works.
The ideas behind this problem
Last problem in this lesson
Go to the next lessonTwo words are anagrams if one can be rearranged into the other, using every letter exactly once.
Worked example#
Are anagram and nagaram anagrams? Count the letters in each:
| letter | in anagram | in nagaram |
|---|---|---|
| a | 3 | 3 |
| n | 1 | 1 |
| g | 1 | 1 |
| r | 1 | 1 |
| m | 1 | 1 |
Every count matches, so yes.
Are rat and car? The first has an r, a and t; the second has a c, a and r. The counts differ, so no.
A different length is an immediate no, since the letters cannot possibly pair up.
Constraints#
1 <= length of each word <= 50000- Both words are lowercase letters only
Input
s is one word. t is one word.
Output
true or false.
Examples
Input
anagram nagaram
Output
true
Both words use three a's, one n, one g, one r and one m.
Input
rat car
Output
false
The letters are not the same, so no rearrangement works.
Input
ab abc
Output
false
Different lengths cannot be anagrams.
Something wrong with this problem? Report an issue
Ready to try it
Write your solution in C, C++, Java or Python and see every test case come back with the time and memory it took.
Free, and it stays free. No card.