Valid Anagram

Easy

Problem

Return true if t is an anagram of s — the same characters with the same counts, possibly in a different order.

Example 1

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

Example 2

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

Test cases

Case 1

Input:    "anagram", "nagaram"
Expected: true

Case 2

Input:    "rat", "car"
Expected: false

Case 3

Input:    "a", "ab"
Expected: false

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution2 approaches

1. Sort both

Time O(n log n)Space O(n)

Anagrams have identical sorted forms.

const isAnagram = (s, t) =>
s.length === t.length && [...s].sort().join('') === [...t].sort().join('');

2. Count array

Time O(n)Space O(1) — 26 letters (use a Map for Unicode)

Increment for s, decrement for t; every count must end at zero.

function isAnagram(s, t) {
if (s.length !== t.length) return false;
const cnt = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
cnt[s.charCodeAt(i) - 97]++;
cnt[t.charCodeAt(i) - 97]--;
}
return cnt.every((c) => c === 0);
}