Skip to main content

17. Valid Anagram

easyAsked at Unity

Check whether two strings are rearrangements of the same characters — the same frequency-table logic Unity uses to validate shader tag consistency between two material property blocks at runtime.

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 exact same characters with the exact same frequencies.

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 each string; sorted anagrams are identical. Simple but O(n log n).

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. Frequency count array

Use a 26-element array indexed by character code. Increment on s, decrement on t. Any non-zero entry means not an anagram.

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:

Unity-specific tips

Unity cares about constant-space guarantees here — the 26-slot array maps cleanly to a fixed-size property block, which is the kind of bounded-memory reasoning the graphics team values in runtime-critical paths.

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

Practice these live with InterviewChamp.AI →