GitHub
Easy

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.

Code

Test Cases

Input 1

Expected Output: true

Input 2

Expected Output: false

Input 3

Expected Output: true

Complexity

Time Complexity: O(n) - Hash map approach: iterate both strings once. Sorting approach: O(n log n) due to sorting.

Space Complexity: O(1) - Hash map stores at most 26 characters (for lowercase English letters), which is constant space. Sorting approach: O(1) if sorting in-place, or O(n) if creating new arrays.