Valid Anagram (Sorting)

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Valid Anagram (Sorting)

Approach

Sort both strings alphabetically and compare. If they are anagrams, their sorted forms will be identical. This is simpler than the hash map approach but trades O(n) time for O(n log n) due to sorting.

Complexity Analysis

Time
O(n log n)
Space
O(n)

Pattern

Sort + Compare

Why It Works

Anagrams are permutations of the same characters. Sorting normalizes any permutation to a canonical form, so two anagrams produce identical sorted strings. The tradeoff vs frequency counting: simpler code but slower for large inputs.

Updated Feb 2026