Visualize the hash map approach to checking if two strings are anagrams.
About this algorithm
Two words are anagrams when one is a rearrangement of the other: the same letters, each used the same number of times. This page decides that in one pass over each word by counting letters in a hash map, adding for the first word and taking away for the second.
Reach for letter counting whenever the question is "same items, any order": anagrams, grouping words that are anagrams of each other, checking whether a ransom note can be built from a magazine. Sorting both words and comparing them also works and needs no map, but it costs O(n log n) instead of O(n). The chaining and linear probing pages show how the map itself works inside; this page treats it as a tool. Two sum is the other classic use, where the map remembers values you have already seen.
If the two words have different lengths they cannot be anagrams, so return false straight away without counting anything.
Go through s one letter at a time and add 1 to that letter's count in the map, creating the entry at 1 the first time a letter appears.
Go through t. For each letter, if it has no entry or its count is already 0, then t uses that letter more often than s does: return false. Otherwise subtract 1.
If t finishes without a failure, every count has returned to 0 and the words are anagrams. With equal lengths and no early exit, nothing can be left over.
The page loads ANAGRAM and NAGARAM, both 7 letters. Counting ANAGRAM gives A = 3, N = 1, G = 1, R = 1 and M = 1. Now walk NAGARAM: N takes its count to 0, A goes to 2, G to 0, A to 1, R to 0, A to 0 and M to 0. All five counts are zero, so the answer is true after 14 letter visits. Pick the RAT and CAR preset to see a failure: the counts are R, A and T at 1 each, and the very first letter of CAR, C, has no entry, so the check stops right there and returns false.
The inputs are turned into capital letters with anything else removed, up to 14 letters each, so "Listen" and "Silent" are compared as LISTEN and SILENT. If you need case or spaces to count, skip that cleaning step.
With only the 26 letters A to Z, a plain array of 26 counters indexed by letter does the same job with less overhead. A map is the general version that works for any characters, including Unicode.
Time: each letter of each word is visited once, and every map update is O(1) on average. Space: the map holds one count per distinct letter, at most 26 here, so it does not grow with the word length (O(k) for an alphabet of k characters).