Valid Anagram
Decide whether two words use exactly the same letters, the same number of times, by counting each letter.
Given two strings sttruetsfalse
Example 1
Output: true
Example 2
Output: false
Explanation: "car" has a c where "rat" has a t.
The Idea
You may know anagrams from word puzzles: "listen" and "silent" are made from the same six letters, only shuffled. Think of each word as a handful of letter tiles. Two words are anagrams when you can lay out the tiles of one and spell the other with nothing missing and nothing left over.
Take Example 1. "anagram" has three a's and one each of g, m, n and r. "nagaram" has exactly the same tiles. In Example 2, "rat" and "car" share an a and an r, but "rat" has a t that "car" lacks, and "car" has a c that "rat" lacks.
So what decides the answer? The order of the letters plays no part. Only one thing matters: for every letter, does it appear as many times in st
Each half of the picture counts the letters of one example. The row labelled "in s" holds the counts for sttruefalse
That last row is the key. Count each letter of st
Solution Approach
Turning that idea into code means settling three things: why counting beats sorting the letters, where the counts are kept, and what to check before counting. One optional part covers text with letters beyond a to z.
Sorting or counting
Is there an even simpler check? Sort the characters of both strings and compare: "anagram" and "nagaram" both sort to "aaagmnr". That works, but sorting n characters takes O(n log n) steps. Counting the letters only needs to look at each character once, so it takes O(n).
One array of counts
Where do the counts live? With only the 26 letters a to z, an array of 26 numbers is enough. Position 0 counts a, position 1 counts b, and so on. In Java, subtracting 'a''c' - 'a'
Two arrays, one per string, would work too. A single array is simpler: add 1 for each letter of st
Checking the lengths first
What if the strings have different lengths? Then some letter must appear more often in the longer one, so the answer is falsei
Optional: letters beyond a to z
What if the text can contain any character, such as é or an emoji? The array version then breaks: 'é' - 'a'HashMap<Integer, Integer>
Java keeps some characters, such as most emoji, as two charcharAts.codePoints()
Java Solution
The method isAnagram
- First, compare
ands.length() , and returnt.length() if they differ.false - Create the array
with 26 entries, all starting at 0.count - Walk both strings in one loop over position
. Add 1 at the position ofi and subtract 1 at the position ofs.charAt(i) .t.charAt(i) - Loop over
. If any entry is not 0, one string has more of that letter, so returncount .false - If every entry is 0, return
.true
The main
public class ValidAnagram {
public static boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++; // letters of s add
count[t.charAt(i) - 'a']--; // letters of t take away
}
for (int c : count) {
if (c != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(isAnagram("anagram", "nagaram"));
System.out.println(isAnagram("rat", "car"));
System.out.println(isAnagram("aab", "abb")); // same letters, different counts
System.out.println(isAnagram("listen", "silent"));
System.out.println(isAnagram("abc", "ab")); // different lengths
System.out.println(isAnagram("", "")); // two empty strings
}
}
Running it prints:
true
false
false
true
false
true
The opening truefalsefalse
"listen" and "silent" give truefalsetrue
The original implementation,
Complexity
The work is one pass over the two strings, plus a check of the 26 counts.
- Time: O(n) for strings of n letters. The loop makes two array updates at each of the n positions, and the final check always takes 26 steps, however long the strings are.
- Space: O(1). The
array has 26 entries for strings of any length. The optional map version needs one entry per distinct character instead.count
To sort a whole list of words into anagram groups, see