Valid Anagram

Easy

Given two strings s and t, return true if t is an anagram of s. An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.

Examples

InputOutput
s = "anagram", t = "nagaram"true
s = "rat", t = "car"false

Python Solution

def is_anagram(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False
    counts = {}
    for c in s:
        counts[c] = counts.get(c, 0) + 1
    for c in t:
        counts[c] = counts.get(c, 0) - 1
        if counts[c] < 0:
            return False
    return True

JavaScript Solution

function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  const counts = {};
  for (const c of s) counts[c] = (counts[c] || 0) + 1;
  for (const c of t) {
    counts[c] = (counts[c] || 0) - 1;
    if (counts[c] < 0) return false;
  }
  return true;
}

Step-by-Step Explanation

  1. Count character frequencies in s.
  2. For each character in t, decrement the count.
  3. If any count goes negative, t has extra characters—not an anagram.

Complexity Analysis

TimeO(n)
SpaceO(1) — at most 26 letters

Tags

StringHash Map

Related Problems

Related Tools

All Problems