Valid Anagram
Given two strings, determine if they are anagrams (contain the same characters with the same frequencies).
Write a function that takes two strings and returns true if they are anagrams of each other, and false otherwise. An anagram is a word formed by rearranging the letters of another word, using all the original letters exactly once.
How to Solve
Count character frequencies in both strings. If the strings have different lengths, they can't be anagrams. Use a hash map to count characters in the first string, then decrement counts while iterating the second string. If all counts reach zero, they're anagrams. Alternatively, sort both strings and compare.
Click to reveal
Example 1:
Input:
s = "anagram"
t = "nagaram"
Output: true
Example 2:
Input:
s = "rat"
t = "car"
Output: false
Example 3:
Input:
s = "listen"
t = "silent"
Output: true