Valid Anagram

Decide whether two words use exactly the same letters, the same number of times, by counting each letter.

Given two strings s and t made of lowercase English letters, return true if t is an anagram of s, and false otherwise. An anagram uses the same letters, each the same number of times, in any order.

Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Explanation: "car" has a c where "rat" has a t.
Solution

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 s as in t? Look at the picture below.

Letter counts. For anagram and nagaram, each letter a, g, m, n, r appears as often in s as in t, so the row s minus t is all zero. For rat and car, the row s minus t is -1 for c and 1 for t.

Each half of the picture counts the letters of one example. The row labelled "in s" holds the counts for s, the row "in t" the counts for t, and the row "s minus t" their difference. On the left, every difference is 0, so the answer is true. On the right, c gets -1 and t gets 1, so the answer is false.

That last row is the key. Count each letter of s as +1 and each letter of t as -1, and the two strings are anagrams exactly when every letter ends at zero.

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' from a letter gives its position, because letters are stored as numbers in alphabet order: 'c' - 'a' is 2.

Two arrays, one per string, would work too. A single array is simpler: add 1 for each letter of s and subtract 1 for each letter of t. It then holds the row "s minus t" from the picture directly, and the last step only checks that every entry is 0.

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 false without counting anything. Checking this first also lets one loop walk both strings together, since position i exists in both.

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' is 136, past the end of the 26 counts. The counts can go in a HashMap<Integer, Integer> instead, from character to count, which holds any character that turns up.

Java keeps some characters, such as most emoji, as two char values, so charAt would see two halves. Each whole character has one number, called its code point, and s.codePoints() gives these numbers one character at a time. Count with those as the map keys.

Java Solution

The method isAnagram works in these steps:

  1. First, compare s.length() and t.length(), and return false if they differ.
  2. Create the array count with 26 entries, all starting at 0.
  3. Walk both strings in one loop over position i. Add 1 at the position of s.charAt(i) and subtract 1 at the position of t.charAt(i).
  4. Loop over count. If any entry is not 0, one string has more of that letter, so return false.
  5. If every entry is 0, return true.

The main method runs both examples, "aab" against "abb", "listen" against "silent", two strings of different lengths, and two empty strings.

Java
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:

Output
true
false
false
true
false
true

The opening true and false match the answers of Example 1 and Example 2. Look at the third line, false for "aab" and "abb". Both use only a and b, so a check of which letters appear would call them anagrams. The counts tell them apart: a ends at 1 and b at -1.

"listen" and "silent" give true. The fifth line, for "abc" and "ab", returns false from the length check before any counting. The last line is true: two empty strings have the same length, the loop never runs, and all 26 counts stay 0.

The original implementation, ValidAnagram.java, is on GitHub.

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 count array has 26 entries for strings of any length. The optional map version needs one entry per distinct character instead.

To sort a whole list of words into anagram groups, see Group Anagrams; to find anagrams inside a longer string, see Find All Anagrams in a String.