Valid Anagram


242. Valid Anagram – LeetCode


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 a different word or phrase, typically using all original letters exactly once.


Examples

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Constraints


Intuition

To check if t is an anagram of s, both strings must:

  1. Be of equal length.

  2. Contain exactly the same frequency of each character.

The problem becomes a character frequency comparison between two strings.


Approach: Frequency Array (Optimized for lowercase English letters)

  1. If s.length() != t.length(), return false.

  2. Initialize a frequency array freq[26] to track character counts.

  3. Traverse both strings simultaneously:

    • Increment freq[s[i] - 'a']

    • Decrement freq[t[i] - 'a']

  4. Finally, check if all elements in freq are zero. If yes, t is an anagram of s.


Java Code

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;

        int[] freq = new int[26];

        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i) - 'a']++;
            freq[t.charAt(i) - 'a']--;
        }

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

        return true;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation: Constant space due to fixed-size array of 26 elements.

Dry Run

Input:

s = "anagram", t = "nagaram"

Steps:


Follow-Up: Unicode Character Support

If s and t can contain Unicode characters, we cannot use a fixed-size array (since there are more than 26 characters).

Solution: Use a HashMap<Character, Integer> instead:

Time and space remain O(n), but the space is dynamic based on input charset.


Conclusion

This problem reinforces the classic frequency-counting technique, useful in problems related to anagrams, permutations, and character set comparisons.

For English letters, the fixed-size array approach is the most optimal.