Valid Anagram
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:** ```typescript isAnagram("anagram", "nagaram") // true isAnagram("rat", "car") // false ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(1) strictly (or O(n) broadly)
We iterate through both strings of length n once. Reading and writing to the Map takes O(1) on average. Overall time complexity is O(n), which is far superior to sorting which takes O(n log n).
Follow-Up Questions Interviewers Ask About Valid Anagram
- What are the trade-offs between sorting the strings vs using a frequency map?
Sorting requires O(n log n) time and O(n) or O(1) space depending on language sort implementation. The frequency map is strictly O(n) time and O(1) space (for fixed alphabets), making it the optimal algorithmic choice. - How would you optimize this for standard lowercase ASCII without allocating Map objects?
Allocate a fixed array of size 26 initialized with zeros (new Int32Array(26)). Increment counts with s.charCodeAt(i) - 97 and decrement with t.charCodeAt(i) - 97. If any value !== 0, it is not an anagram. - What if the strings contain Unicode or multi-byte characters like emojis?
You must use Array.from(s) or Intl.Segmenter rather than naive indexing or charCodeAt, because multi-byte UTF-16 surrogate pairs will be split incorrectly by standard string iteration.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.