Skip to main content

242. Valid Anagram

easyAsked at Duolingo

Determine whether two strings are anagrams of each other — a pattern that mirrors how Duolingo's vocabulary engine checks if a learner rearranged the correct letters to spell a target word, making character-frequency maps the go-to tool.

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 is a word formed by rearranging all characters of the original word exactly once.

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

Explanation: Both contain exactly a×3, n×1, g×1, r×1, m×1.

Example 2

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

Approaches

1. Brute force — sort both strings

Sort both strings and compare; equal strings means they are anagrams.

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

Tradeoff:

2. Optimal — character frequency map

Count character frequencies in s, decrement for t, then verify all counts are zero.

Time
O(n)
Space
O(1)
function isAnagram(s, t) {
  if (s.length !== t.length) return false;
  const freq = new Array(26).fill(0);
  const a = 'a'.charCodeAt(0);
  for (let i = 0; i < s.length; i++) {
    freq[s.charCodeAt(i) - a]++;
    freq[t.charCodeAt(i) - a]--;
  }
  return freq.every(c => c === 0);
}

Tradeoff:

Duolingo-specific tips

Duolingo's word-matching exercises depend on exactly this pattern — when a learner types a shuffled answer, the backend validates it via frequency comparison, not sort. Interviewers want you to arrive at the O(1)-space array approach over a Map, and to call out the early-exit length check. Articulate why fixed-alphabet arrays beat a Map here: cache locality and no hashing overhead.

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 Duolingo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →