Skip to main content

26. Valid Anagram

easyAsked at Glassdoor

Glassdoor's search team normalizes job-title keywords so that 'Engineer Software' and 'Software Engineer' hit the same results — this character-frequency comparison is the pattern behind that normalization and a common screen opener.

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 all the same characters the same number of times.

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 both strings

Sort the characters of both strings and compare. O(n log n) time, simple to implement.

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. Character frequency map

Count character frequencies for s, then decrement for t. If any count is non-zero at the end, the strings are not anagrams. O(n) time, O(1) space (bounded by alphabet size 26).

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

Tradeoff:

Glassdoor-specific tips

Glassdoor interviewers use this problem to gauge whether you handle the Unicode follow-up: 'what if the input isn't lowercase ASCII?' The sorted-string approach handles Unicode automatically; the fixed-array approach needs to switch to a Map. Mention that distinction without being asked — it signals you think about data assumptions, which matters a lot for a platform where user content arrives in many languages and formats.

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

Practice these live with InterviewChamp.AI →