242. Valid Anagram LeetCode Solution
In this guide, you will get 242. Valid Anagram LeetCode Solution with the best time and space complexity. The solution to Valid Anagram problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Valid Anagram solution in C++
- Valid Anagram solution in Java
- Valid Anagram solution in Python
- Additional Resources

Problem Statement of Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104
s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(26) = O(1)
242. Valid Anagram LeetCode Solution in C++
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
vector<int> count(26);
for (const char c : s)
++count[c - 'a'];
for (const char c : t) {
if (count[c - 'a'] == 0)
return false;
--count[c - 'a'];
}
return true;
}
};
/* code provided by PROGIEZ */
242. Valid Anagram LeetCode Solution in Java
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
int[] count = new int[26];
for (final char c : s.toCharArray())
++count[c - 'a'];
for (final char c : t.toCharArray()) {
if (count[c - 'a'] == 0)
return false;
--count[c - 'a'];
}
return true;
}
}
// code provided by PROGIEZ
242. Valid Anagram LeetCode Solution in Python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count = collections.Counter(s)
count.subtract(collections.Counter(t))
return all(freq == 0 for freq in count.values())
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.