242. Valid Anagram

Intuition

Two strings are anagrams if they contain the same characters with the exact same frequency, just possibly in a different order.

So, we don’t care where characters are — just how many times each character appears in both strings.

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(N)\text{O}(N)

Code

public boolean isAnagram(String firstString, String secondString) {
    // Arrays to store character frequencies
    int[] freqFirst = new int[26];
    int[] freqSecond = new int[26];

    int lengthFirst = firstString.length();
    int lengthSecond = secondString.length();

    // If lengths are different, they can't be anagrams
    if (lengthFirst != lengthSecond) return false;

    // Count characters in both strings
    for (int i = 0; i < lengthFirst; ++i) {
        freqFirst[firstString.charAt(i) - 'a']++;
        freqSecond[secondString.charAt(i) - 'a']++;
    }

    // Compare frequency of each character
    for (int i = 0; i < 26; ++i) {
        if (freqFirst[i] != freqSecond[i]) return false;
    }

    return true; // All counts matched => anagram
}

Last updated