Valid Anagram
EasyNeetCode 150Top Interview 150 Arrays & HashingtcsAmadeusNokiaYelpAmerican ExpressProblem
Two strings are anagrams when one can be rearranged into the other: they use exactly the same letters, each the same number of times.
Given strings s and t, return true if t is an anagram
of s, otherwise false.
Constraints
- 1 ≤ s.length, t.length ≤ 5 · 10⁴
- s and t use lowercase English letters
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: One pass over s and one pass over t, each step is an O(1) map update.
Space: The map holds at most one entry per distinct letter, and the alphabet is fixed at 26.
Count every letter of s going up, then walk t counting the same letters going down. With equal lengths, any letter that t has too many of drives a count below zero, and that is the only way to fail.