Explorer
JavaScript

Check if two strings are anagrams of each other.

Problem Statement

Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Examples

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

Output: true

Explanation: Both strings contain the exact same character counts.

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

Output: false

Explanation: The characters and their counts do not match.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: An anagram contains the exact same frequency of each character. šŸ’” Hint 2: First check if lengths match: s.length === t.length. šŸ’” Hint 3: Use a frequency array of size 26. Increment for s and decrement for t. Every entry must end at 0.

Editorial & Approach

Problem Overview & Intuition

Two strings are anagrams if and only if their character frequencies are identical. Using a 26-element array for lowercase English letters, increment counts for characters in s and decrement for t in a single pass.

Step-by-Step Approach

  1. If s.length !== t.length, return false.
  2. Allocate frequency array of size 26 filled with 0.
  3. Iterate i from 0 to s.length - 1:
  4. Increment count[s.charCodeAt(i) - 97]++ and decrement count[t.charCodeAt(i) - 97]--.
  5. Return true if all entries in count are 0; otherwise false.

Optimal Implementation (JavaScript)

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

Complexity Analysis

Time Complexity O(N) — single pass of length N.
Space Complexity O(1) — fixed array of size 26.

Edge Cases & Corner Traps Handled

  • Different length strings: false.
  • Identical strings: true.
  • Same letters different frequencies: "aab" and "abb" -> false.

Check if two strings are anagram of each other

Easy
Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`, and `false` otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example Scenarios
1Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Explanation:

Both strings contain the exact same character counts.

2Example 2
Input: s = "rat", t = "car"
Output: false
Explanation:

The characters and their counts do not match.

Editor
Loading Editor...
s =
"anagram"
t =
"nagaram"
Output:Click "Run" above to execute and verify your code here.
true