Problem

Given two strings s and t, return true if t is an anagram of s (uses the exact same characters in any order).

Example

Input:  s = "anagram", t = "nagaram"
Output: true
Input:  s = "rat", t = "car"
Output: false

Solution

Count the frequency of each character. Anagrams have identical character counts.

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if counts.get(ch, 0) == 0:
            return False
        counts[ch] -= 1
    return True
function isAnagram(s, t) {
    if (s.length !== t.length) return false;
    const counts = {};
    for (const ch of s) counts[ch] = (counts[ch] || 0) + 1;
    for (const ch of t) {
        if (!counts[ch]) return false;
        counts[ch]--;
    }
    return true;
}
bool isAnagram(string s, string t) {
    if (s.size() != t.size()) return false;
    int counts[26] = {0};
    for (char ch : s) counts[ch - 'a']++;
    for (char ch : t) {
        if (--counts[ch - 'a'] < 0) return false;
    }
    return true;
}
public boolean isAnagram(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;
}

Complexity

  • Time: O(n)
  • Space: O(1) for fixed alphabet

Explanation

For lowercase English letters, a fixed-size array of 26 is faster than a hash map. Increment for one string, decrement for the other. If anything goes negative, they’re not anagrams.

Share this article

Comments

Join the discussion. Got a question, found an issue, or want to share your experience?

Leave a Comment

Your email stays private. We just use it for replies.

Nothing to preview yet.

Use **bold**, *italic*, `code`, ```code blocks```, [link](url), > quote, - list