Code Logo

Valid Anagram

Published at16 Mar 2026
Easy 18 views
Like0

You are given two strings and need to decide whether one is an anagram of the other.

That means they must contain exactly the same characters with exactly the same counts. The order does not matter, but the frequency does. If one string has an extra letter or is missing a copy of some letter, the answer is false.

For example, s = "anagram" and t = "nagaram" return true because both strings use the same letters the same number of times. But s = "rat" and t = "car" return false because the letters do not match.

So the task is to compare the full character inventory of both strings, not their order.

For Unicode strings or case-insensitive anagrams, a general hash map is needed instead of the fixed-size array. The hash map approach works for any character set.

An alternate solution sorts both strings and compares them. If the sorted versions are equal, they are anagrams. This runs in O(n log n) time compared to the hash map approach's O(n), but uses O(1) space (depending on the sorting algorithm).

Example Input & Output

Example 1
Input
s = "anagram", t = "nagaram"
Output
true
Explanation

Both strings contain the same letters with the same counts.

Example 2
Input
s = "rat", t = "car"
Output
false
Explanation

The letters do not match.

Example 3
Input
s = "aacc", t = "ccac"
Output
false
Explanation

The character counts are different.

Algorithm Flow

Recommendation Algorithm Flow for Valid Anagram

Solution Approach

Count the frequency of each character in both strings and compare the frequency maps. If they are identical, the strings are anagrams.

function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  var freq = {};
  for (var i = 0; i < s.length; i++) {
    freq[s[i]] = (freq[s[i]] || 0) + 1;
  }
  for (var i = 0; i < t.length; i++) {
    if (!freq[t[i]]) return false;
    freq[t[i]]--;
  }
  return true;
}

Count characters in the first string using a frequency map. Then iterate through the second string, decrementing counts. If any character is missing or has an extra occurrence, the strings are not anagrams.

Time complexity is O(n), space complexity is O(k) where k is the alphabet size.

Best Answers

java
import java.util.*;
class Solution {
    public boolean solution(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] counts = new int[26];
        for (char ch : s.toCharArray()) counts[ch - 'a']++;
        for (char ch : t.toCharArray()) {
            if (--counts[ch - 'a'] < 0) return false;
        }
        return true;
    }
}