Algorithms

Valid Anagram

EasyLast updated: 02/05/2026, 16:00:00 PST
01

Problem Statement

Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram is a word or phrase formed by rearranging the letters of another (same characters with the same counts, possibly different order). Assume the strings contain only lowercase English letters (or clarify the character set).

  • If s and t have different lengths, they cannot be anagrams. We can count the frequency of each character in s, then decrement for each character in t; if all counts are zero, they are anagrams.
02

Key Observations

  • Frequency count: Use an array count[26] (or a map). For each character in s, count[c-'a']++. For each character in t, count[c-'a']--. If any count[i] != 0, return false; else return true. This is O(n) time and O(1) space (fixed 26).
  • Sorting: Sort both strings and compare. O(n log n) time. The count approach is preferred for O(n).
03

Approach

High-level: If s.length() != t.length() return false. Count chars in s (increment); count chars in t (decrement). If any count is non-zero, return false. Return true.

Steps:

  1. if s.length() != t.length() return false. int[] count = new int[26].
  2. For each c in s: count[c-'a']++. For each c in t: count[c-'a']--.
  3. For each x in count: if x != 0 return false. return true.
04

Implementation

Java
public boolean isAnagram(String s, String t) {

    if (s.length() != t.length()) {
        return false;
    }

    int[] count = new int[26];

    for (char c : s.toCharArray()) {
        count[c - 'a']++;
    }

    for (char c : t.toCharArray()) {
        count[c - 'a']--;
    }

    for (int x : count) {
        if (x != 0) {
            return false;
        }
    }

    return true;
}
05

Test Cases

Example 1

Input
s = "anagram", t = "nagaram"
Expected
true
Explanation
Same chars and counts.
06

Complexity Analysis

  • Time: O(n).
  • Space: O(1) (26 letters).
07

Follow-ups

  • Group anagrams (hash by sorted string or count signature).