Skip to main content

16. Valid Anagram

easyAsked at Quora

Determine whether two strings are anagrams — Quora uses this frequency-counting pattern to detect near-duplicate questions where word order differs but vocabulary is identical.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given two strings s and t, return true if t is an anagram of s, and false otherwise. An anagram uses the same characters with the same frequencies in any order.

Constraints

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters

Examples

Example 1

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

Example 2

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

Approaches

1. Sort and compare

Sort both strings alphabetically and compare them character by character.

Time
O(n log n)
Space
O(1)
function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  return s.split('').sort().join('') === t.split('').sort().join('');
}

Tradeoff:

2. Frequency count (hash map)

Count character frequencies in s, decrement for t; any non-zero entry means not an anagram. Single hash-map, two passes.

Time
O(n)
Space
O(1)
function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  const freq = {};
  for (const ch of s) freq[ch] = (freq[ch] || 0) + 1;
  for (const ch of t) {
    if (!freq[ch]) return false;
    freq[ch]--;
  }
  return true;
}

Tradeoff:

Quora-specific tips

Quora's duplicate-question detection uses this exact frequency-map pattern extended to n-grams. Show that you can generalise: what happens with Unicode or multibyte characters? That follow-up distinguishes mid-level from senior candidates.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Valid Anagram and other Quora interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →