beginner · hashing · counting · strings

Same letters, different order?

Problem

Two lowercase words are anagrams if one is a rearrangement of the other, using every letter exactly as often. Decide whether two words are anagrams.

Constraints

  • each word has 0 to 16 letters a–z

Examples

"listen", "silent" → true

"rat", "car" → false

Show the solution

Letter counts up and down

Equal lengths plus no letter used more in the second word than in the first means the counts are identical.

Why it is correct

With equal lengths, if no count ever goes negative while subtracting, every count ends at exactly 0 (a positive leftover would force a negative elsewhere).

Complexity

Time O(n) expected, extra space O(alphabet). One pass over each word with expected-O(1) map updates.

For contrast: Sort both and compare. That costs O(n log n) time and O(n) space.

Edge cases

  • Different lengths: false immediately.
  • Two empty words: true.
  • Repeated letters must match in number, not just in presence.

Common mistakes

  • Checking only that the same letters appear (ignoring counts).
  • Forgetting the length check, then missing leftover letters.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class Anagram
{
    /// <summary>Whether two words use exactly the same letters, as often. Expected O(n) time.</summary>
    public static bool IsAnagram(string first, string second)
    {
        if (first.Length != second.Length) return false;
        var count = new Dictionary<char, int>();
        foreach (char c in first)
            count[c] = count.GetValueOrDefault(c) + 1;
        foreach (char c in second)
        {
            count[c] = count.GetValueOrDefault(c) - 1;
            if (count[c] < 0) return false; // the second word uses c more often
        }
        return true;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/Anagram.cs

def is_anagram(first: str, second: str) -> bool:
    """Whether two words use exactly the same letters, as often. Expected O(n) time."""
    if len(first) != len(second):
        return False
    count: dict[str, int] = {}
    for char in first:
        count[char] = count.get(char, 0) + 1
    for char in second:
        count[char] = count.get(char, 0) - 1
        if count[char] < 0:  # the second word uses char more often
            return False
    return True

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/anagram.py

package dev.bekadan.dsa.problems;
 
import java.util.HashMap;
import java.util.Map;
 
public final class Anagram {
    private Anagram() {
    }
 
    /** Whether two words use exactly the same letters, as often. Expected O(n) time. */
    public static boolean isAnagram(String first, String second) {
        if (first.length() != second.length()) {
            return false;
        }
        Map<Character, Integer> count = new HashMap<>();
        for (char c : first.toCharArray()) {
            count.merge(c, 1, Integer::sum);
        }
        for (char c : second.toCharArray()) {
            int left = count.merge(c, -1, Integer::sum);
            if (left < 0) { // the second word uses c more often
                return false;
            }
        }
        return true;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/Anagram.java

#pragma once
 
#include <string_view>
#include <unordered_map>
 
namespace bekadan::dsa::problems {
 
// Whether two words use exactly the same letters, as often. Expected O(n) time.
inline bool is_anagram(std::string_view first, std::string_view second) {
    if (first.size() != second.size()) return false;
    std::unordered_map<char, int> count;
    for (char c : first)
        ++count[c];
    for (char c : second) {
        const int left = --count[c];
        if (left < 0) return false;  // the second word uses c more often
    }
    return true;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/anagram.hpp