You get two strings, s and t. Return true if t is an anagram of s. An anagram uses the same letters, the same number of times, in any order.
DSA Animator › DSA Revision › Strings › Valid Anagram
Remember: anagram means equal letter counts. One array of 26 counts: add for s, subtract for t. The video solves Valid Anagram (LeetCode 242, Easy) with the Frequency Count pattern from the Strings topic, and you can replay every step in the interactive Valid Anagram animation.
You get two strings, s and t. Return true if t is an anagram of s. An anagram uses the same letters, the same number of times, in any order.
anagram and nagaram both have three a, and one each of n, g, r and m. So the answer is true. But rat and car differ, with t in one and c in the other, so that answer is false.
The simplest approach sorts both strings and compares them. It works, but sorting takes O of n log n. We can do it in O of n.
Count how many times each letter appears. Add 1 for every letter of s. Subtract 1 for every letter of t. If every count ends at 0, the strings are anagrams. And if the lengths differ, return false right away.
First, count s. a appears three times, and n, g, r and m once each. Now read t. n arrives, so the count of n drops to 0. a arrives, so a drops to 2. g arrives, so g drops to 0. Another a, so a drops to 1. r arrives, so r drops to 0 as well. Another a, and a reaches 0. Finally m, and m reaches 0. Every count is 0, so the answer is true.
In code, check the lengths first. Then create a count array of size 26. In one loop, add 1 for the letter of s, and subtract 1 for the letter of t. Finally, if any count is not 0, return false, otherwise return true. Time is O of n, and space is O of 1, because the array always has 26 slots.
Remember: anagram means equal letter counts. One array of 26 counts: add for s, subtract for t.