DSA and coding Level 1 This level · 6 of 19
Easy dsa arrays

Valid Anagram

The 30 second answer

Two strings are anagrams when every character appears the same number of times in both. For lowercase English letters I use an int array of 26: increment for the first string, decrement for the second, and check that everything is back to zero. I return false early if the lengths differ. For full Unicode I would switch to a HashMap of code points.

Could you say this in an interview?

Problem Given two strings, decide whether one is a rearrangement of the other's letters. Original: LeetCode 242: Valid Anagram.

Understanding the prompt "Anagram" means the same letters with the same counts. Order doesn't matter. Ask which characters can appear: the base problem uses lowercase English letters.

Pattern recognition "Same characters, same counts" is frequency counting. With a small fixed alphabet, an int array is simpler and faster than a map.

Brute force Sort both strings and compare them: O(n log n). That is acceptable, but it isn't the best answer.

Optimal One count array: add for s, subtract for t, and require all zeros. Check the lengths first, so mismatched lengths exit immediately.

Alternatives Use a HashMap of code points for full Unicode. String.codePoints() handles characters outside the Basic Multilingual Plane, which charAt splits into two chars.

Java solution

public class ValidAnagram {
    static boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        var count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
            count[t.charAt(i) - 'a']--;
        }
        for (int c : count) {
            if (c != 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("anagram", "nagaram")); // true
        System.out.println(isAnagram("rat", "car"));         // false
        System.out.println(isAnagram("a", "ab"));            // false
    }
}

Complexity O(n) time. O(1) extra space, because the array has a fixed size of 26.

Edge cases

  • Different lengths.
  • Empty strings, which count as anagrams of each other.
  • Characters outside a to z, which would break the array index: confirm the alphabet first.

Follow-ups

  • Unicode input: use a map of code points.
  • Group many words by anagram: see Group Anagrams below.
  • Find every anagram of a pattern inside a text: use a fixed sliding window.

Tests ("anagram", "nagaram") returns true. ("rat", "car") returns false. ("a", "ab") returns false because the lengths differ.

How to say it in the interview "If the lengths differ, it's false. Otherwise I count letters in an int array of 26, plus for s and minus for t, and check that everything returns to zero. O(n) time and constant space. For Unicode I'd use a map of code points."

Sources (2)
  1. LeetCode 242: Valid Anagramleetcode.com
  2. Java SE 17 API: String.codePointsdocs.oracle.com
Previous
Next