Data Structures19 sections · 729 units
Open in Course

Valid Anagram - Algorithm

Two approaches

Two ways to solve this:

1.1. Build frequency maps for both strings, compare them. Time: O(n)O(n), Space: O(k)O(k) where kk is alphabet size.

2.2. Build one frequency map for ss, then decrement for each character in tt. If any count goes negative or non-zero counts remain, not an anagram. Both work. The second uses less space if you're careful.