18 / 19

How do you check if two strings are anagrams of each other?

Difficulty: 2/10

Anagram Detection

Two strings are anagrams when they contain the same characters with the same frequencies, assuming the same normalization rules. The efficient approach is to count character frequencies in one string and decrement them using the second string.

javascript
  1. 1

    Time complexity: O(n).

  2. 2

    Auxiliary space: O(k), where k is the character set size or number of distinct characters.

  3. 3

    Sorting both strings provides O(n log n) time but is usually less efficient.

  4. 4

    Case sensitivity, whitespace, Unicode normalization, and punctuation should be specified.

Follow-up Questions

  • How would you handle Unicode characters?
  • Can you solve it by sorting?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.