AlgoTales · Roadmap

Anagrams

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Two words are anagrams if they use exactly the same letters in a different order, like listen and silent. Counting letters in each word and comparing the tallies tells you quickly, without trying every shuffle, and also lets you group many words at once.

Practical use cases

  • Web app: Grouping words for a Scrabble helper. A word-game site lets players type their tiles and shows all dictionary words made from them. For every dictionary word, the site keeps a letter fingerprint, such as the letters sorted. Words sharing a fingerprint are anagrams, so the answer is a single lookup.
  • Web app: Duplicate detection in a name list. A registration page finds entries whose names are the same letters reordered, such as a typed Ravi Kumar and Kumar Ravi. Comparing letter counts flags likely duplicates without comparing every name against every other name by hand. Cleaning the list this way means people are not emailed twice.
  • System: Plagiarism hints and bioinformatics. Text checkers use letter and word counts as a rough fingerprint to find suspicious matches. Biologists compare the makeup of short DNA fragments by counting letters before doing a costly detailed comparison. Counting first filters out obvious non-matches cheaply, so the expensive detailed comparison runs only on a few likely pairs.

The story: The Scrambled Name Boards

At the school fair, Kabir made two name boards: one said LISTEN and the other said SILENT. "Same letters, different order!" he announced proudly. His friend Aarav frowned. "Prove it." Kabir began shuffling the letter tiles of one word, trying to turn it into the other, and the crowd lost patience.

Mira stepped in with the tally sheet she remembered from the tile game. "Walk over the first word and add one to each letter's box. Then walk over the second word and take one away. If the words really contain the same letters, every box will end at zero."

They tried it. L, I, S, T, E, N went up by one each; then S, I, L, E, N, T brought each of them back down. All zeros! When Aarav tried it with LISTEN and SILVER, the box for T stayed at 1 and the box for V dropped to minus one, and the game was over fast. Two words that are rearrangements of each other are anagrams.

How to spot this problem, and where you need it

You need to decide whether two pieces of text are made of the same characters, or group many words by their letters, and trying every reordering is impossible.

Signs you need it

  • The problem says anagram, rearrange the letters, same characters in any order, or group words that are scrambles of each other.
  • You compare two strings by sorting both, over millions of words, and the cost adds up.
  • You want a quick fingerprint that does not change when letters are shuffled.

Where to use it in a project

  • Word games, spelling helpers and crossword tools that search a dictionary by available letters.
  • Data cleaning that groups near-duplicate names, tags or product titles that differ only in order.

The solution

Count how many times each letter appears in the first word, then subtract the counts for the second word, or build a second tally and compare. If every count matches, they are anagrams. To group many words, turn each word into its fingerprint, such as its sorted letters or its tally, and use that fingerprint as the key in a keyed array, collecting the words under each key.

Payoff: Before: trying every shuffle, which explodes even for 10-letter words. After: one counting pass per word and a single lookup to group them.

Explain it like I am 8

Imagine two bags of letter tiles. If you can pour both bags onto the table and find exactly the same tiles in both, they are anagrams. Counting is just a faster way of comparing the bags than shuffling the tiles.

How it works, step by step

  1. Check the lengths first. Different lengths can never be anagrams, so say no immediately.
  2. Make a tally of letter counts (26 boxes for a to z, or a map).
  3. Add one for every letter of the first word.
  4. Subtract one for every letter of the second word. If a box ever drops below zero, answer no.
  5. If all boxes finish at zero (guaranteed when the lengths match and nothing went negative), they are anagrams.

The code in four languages

PHP

<?php
// Anagram check with a letter tally: add for word 1, subtract for word 2.
function isAnagram(string $a, string $b): bool {
    if (strlen($a) !== strlen($b)) {
        return false;                           // different lengths: impossible
    }
    $tally = [];
    for ($i = 0; $i < strlen($a); $i++) {
        $tally[$a[$i]] = ($tally[$a[$i]] ?? 0) + 1;     // add one
    }
    for ($i = 0; $i < strlen($b); $i++) {
        $tally[$b[$i]] = ($tally[$b[$i]] ?? 0) - 1;     // take one away
        if ($tally[$b[$i]] < 0) {
            return false;                       // word 2 has an extra letter
        }
    }
    return true;                                // all boxes ended at zero
}

echo "listen / silent: " . var_export(isAnagram("listen", "silent"), true) . "\n";
echo "listen / silver: " . var_export(isAnagram("listen", "silver"), true) . "\n";

JavaScript

// Anagram check with a letter tally: add for word 1, subtract for word 2.
function isAnagram(a, b) {
  if (a.length !== b.length) {
    return false;                               // different lengths: impossible
  }
  const tally = {};
  for (const ch of a) {
    tally[ch] = (tally[ch] || 0) + 1;           // add one
  }
  for (const ch of b) {
    tally[ch] = (tally[ch] || 0) - 1;           // take one away
    if (tally[ch] < 0) {
      return false;                             // word 2 has an extra letter
    }
  }
  return true;                                  // all boxes ended at zero
}

console.log('listen / silent: ' + isAnagram('listen', 'silent'));
console.log('listen / silver: ' + isAnagram('listen', 'silver'));

Java

import java.util.*;

public class Main {
    // Anagram check with a letter tally: add for word 1, subtract for word 2.
    static boolean isAnagram(String a, String b) {
        if (a.length() != b.length()) {
            return false;                                   // different lengths: impossible
        }
        Map<Character, Integer> tally = new HashMap<>();
        for (char ch : a.toCharArray()) {
            tally.merge(ch, 1, Integer::sum);               // add one
        }
        for (char ch : b.toCharArray()) {
            int left = tally.getOrDefault(ch, 0) - 1;       // take one away
            tally.put(ch, left);
            if (left < 0) {
                return false;                               // word 2 has an extra letter
            }
        }
        return true;                                        // all boxes ended at zero
    }

    public static void main(String[] args) {
        System.out.println("listen / silent: " + isAnagram("listen", "silent"));   // true
        System.out.println("listen / silver: " + isAnagram("listen", "silver"));   // false
    }
}

Go

package main

import "fmt"

// isAnagram checks with a letter tally: add for word 1, subtract for word 2.
func isAnagram(a, b string) bool {
	if len(a) != len(b) {
		return false // different lengths: impossible
	}
	tally := map[rune]int{}
	for _, ch := range a {
		tally[ch]++ // add one
	}
	for _, ch := range b {
		tally[ch]-- // take one away
		if tally[ch] < 0 {
			return false // word 2 has an extra letter
		}
	}
	return true // all boxes ended at zero
}

func main() {
	fmt.Println("listen / silent:", isAnagram("listen", "silent")) // true
	fmt.Println("listen / silver:", isAnagram("listen", "silver")) // false
}

Time: O(n) · Extra space: O(k). Two quick passes. Sorting both words and comparing also works but costs more time (O(n log n)).

Watch out for

  • Skipping the length check. "AAB" against "AB" must be rejected before counting.
  • Comparing two words with different capital letters: lower-case first if "Listen" and "silent" should match.

Quick check

  1. Which pair are anagrams?
    • TEA and TEAS
    • STOP and POTS
    • CAT and CUT
  2. While subtracting for word 2, a box drops below zero. What does it mean?
    • Word 2 has a letter that word 1 lacks
    • They are anagrams
    • We must restart
  3. What is a quick first check before counting?
    • Compare the first letters
    • Reverse both words
    • Compare the lengths