Valid Anagram

๐ Problem Statement
Given two strings
s
andt
, returntrue
ift
is an anagram ofs
, andfalse
otherwise.
๐ง What is an Anagram?
An anagram is a word or phrase formed by rearranging the letters of another.
For example:
"anagram"
and"nagaram"
are anagrams โ"rat"
and"car"
are not โ
โ Constraints
Both strings consist of lowercase English letters only.
Their length is between 1 and 50,000 characters.
๐งญ Approach 1: Sorting
๐ก Idea
If two strings are anagrams, sorting them should give the same result.
๐งพ Steps
If lengths of
s
andt
are not equal โ returnfalse
.Sort both strings.
Compare them.
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
๐งช Time & Space
Time: O(n log n) (due to sorting)
Space: O(1) extra (if sorting in-place)
๐ฅ Approach 2: Optimal Hashing (Using Frequency Count)
๐ก Idea
Count how many times each letter appears in s
and t
. If all counts match, they're anagrams.
๐งพ Steps
If lengths differ โ return false.
Create an integer array of size 26 (for letters aโz).
For every character in
s
, increment count.For every character in
t
, decrement count.If all counts are zero โ they are anagrams.
#include <algorithm> // for transform
#include <cctype> // for tolower
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
// Convert to lowercase to handle upper/lowercase
transform(s.begin(), s.end(), s.begin(), ::tolower);
transform(t.begin(), t.end(), t.begin(), ::tolower);
int count[26] = {0};
for (int i = 0; i < s.length(); i++) {
count[s[i] - 'a']++;
count[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) return false;
}
return true;
}
๐งช Time & Space
Time: O(n)
Space: O(1) (fixed 26-letter count array)
problem link: https://leetcode.com/problems/valid-anagram/description/
Subscribe to my newsletter
Read articles from Nikhitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nikhitha
Nikhitha
๐ Software Developer | DSA Enthusiast | Problem Solver ๐น Sharing daily DSA solutions, coding insights, and interview prep ๐น Passionate about writing optimized & bug-free code