Introduction
The Valid Anagram problem is a very common DSA interview question based on strings and hashing. It is often asked whether a candidate can compare characters efficiently.
In simple words, this problem asks you to check whether two strings are anagrams of each other or not.
What is an Anagram?
An anagram is formed when two strings contain exactly the same characters with the same frequency, but the order of characters can be different.
This means:
Both strings must have the same length
Each character must appear the same number of times in both strings
Examples of Anagrams
"listen" and "silent"
"rat" and "tar"
"evil" and "vile"
Not Anagrams
"hello" and "world"
"cat" and "car"
What is the Valid Anagram Problem?
You are given two strings s and t. Your task is to check whether t is an anagram of s.
Example
Input: s = "anagram", t = "nagaram"
Output: true
Explanation
Both strings contain the same characters with the same frequency, so they are valid anagrams.
Brute Force Approach (Simple but Inefficient)
A basic approach is to sort both strings and then compare them.
Problems with Brute Force
Sorting takes extra time
Time Complexity becomes O(n log n)
While this approach works, interviews usually expect a better solution.
Optimized Approach Using Hashing
The most efficient way to solve this problem is by using Hashing.
Key Idea
Count the frequency of each character in both strings
Compare the counts
If all counts match, the strings are anagrams
This avoids sorting and improves performance.
Step-by-Step Explanation
Steps:
If lengths of both strings are different, return false
Create a frequency map for characters
Traverse the first string and increase character count
Traverse the second string and decrease character count
If any count becomes negative, return false
If all checks pass, return true
Dry Run Example
Strings: s = "anagram", t = "nagaram"
Join the conversation! Your thoughts help the community grow.