NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 49. Group AnagramsMedium
  • 13. Roman to IntegerEasy
  • 217. Contains DuplicateEasy
  • 347. Top K Frequent ElementsMedium
  • 1. Two SumEasy

242. Valid Anagram

Easy
Hash TableStringSorting
Companies:
Amazon
Answered: Feb 27, 2026
View on LeetCode

Problem Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Examples

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?


Solutions

Complexity Analysis

Time Complexity:O(n2)

The time complexity is O(n2)O(n^{2})O(n2) because for each character in string s, we potentially search through the list t_list to find and remove the character, which takes O(n)O(n)O(n) time. Since we do this for all characters in s, which has n characters, the overall time complexity is O(n2)O(n^{2})O(n2).

Space Complexity:O(n)

The space complexity is O(n)O(n)O(n) because we create a list t_list that stores all characters of string t.

The brute force approach checks if the two strings have the same length. If they don't, they cannot be anagrams, so we return false. Then, we convert the second string t into a list (or array) to allow for easy removal of characters. We iterate through each character in the first string s, checking if it exists in the list of characters from t. If it does, we remove that character from the list. If it doesn't, we return false immediately. If we successfully check all characters in s without returning false, then s and t are anagrams, and we return true.

Complexity Analysis

Time Complexity:O(nlogn)

The time complexity is O(nlog⁡n)O(n \log n)O(nlogn) because sorting each string takes O(nlog⁡n)O(n \log n)O(nlogn) time, and we do this for both strings.

Space Complexity:O(n)

The space complexity is O(n)O(n)O(n) because the sorting algorithm may require additional space to sort the characters of the strings.

In this approach, we first check if the two strings have the same length. If they don't, we return false immediately. Then, we sort both strings and compare the sorted versions. If the sorted versions are identical, it means that s and t are anagrams of each other, and we return true. Otherwise, we return false.

Complexity Analysis

Time Complexity:O(n)

We iterate through each string once, so the time complexity is O(n)O(n)O(n), where n is the length of the strings.

Space Complexity:O(1)

The space complexity is O(1)O(1)O(1) because the hash maps will at most store 26 keys (for lowercase English letters), which is a constant amount of space.

In this approach, we first check if the two strings have the same length. If they don't, we return false immediately. Then, we create two hash maps (dictionaries) to count the frequency of each character in both strings. We iterate through each character in both strings simultaneously and update the counts in the respective hash maps. Finally, we compare the two hash maps. If they are identical, it means that s and t are anagrams of each other, and we return true. Otherwise, we return false.

Complexity Analysis

Time Complexity:O(n2)

In the worst case, for each unique character in s, we call split on both strings, which takes O(n)O(n)O(n) time. Since there are at most 26 unique characters (for lowercase English letters), the overall time complexity is O(n2)O(n^{2})O(n2).

Space Complexity:O(1)

The space complexity is O(1)O(1)O(1) because the set of unique characters will at most contain 26 characters, which is a constant amount of space.

In this approach, we first check if the two strings have the same length. If they don't, we return false immediately. Then, we create a set of unique characters from string s. We iterate through each unique character and count its frequency in both strings using the count method (or by splitting the string and counting the occurrences). If the frequency of any character does not match between the two strings, we return false. If all characters have matching frequencies, we return true.

Complexity Analysis

Time Complexity:O(n)

We iterate through both strings once, so the time complexity is O(n)O(n)O(n), where n is the length of the strings. [Explain time complexity here]

Space Complexity:O(1)

The space complexity is O(1)O(1)O(1) because the fixed-size array has a constant size of 26, regardless of the input size.

In this approach, we first check if the two strings have the same length. If they don't, we return false immediately. We then create a fixed-size array of length 26 to count the frequency of each character (assuming only lowercase English letters). We iterate through both strings simultaneously, incrementing the count for characters in s and decrementing the count for characters in t. Finally, we check if all counts are zero. If any count is not zero, it means that s and t are not anagrams, and we return false. If all counts are zero, we return true.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Brute Force
O(n2)O(n^{2})O(n2)O(1)O(1)O(1)Simple to understand and implementInefficient for large inputs
Sorting
O(nlog⁡n)O(n \log n)O(nlogn)O(1)O(1)O(1) if sorting in-place, O(n)O(n)O(n) otherwiseEasy to implement and understandSlower than linear time solutions
Hash Map (Dictionary)
O(n)O(n)O(n)O(k)O(k)O(k) where k is the number of unique characters in the stringsLinear time complexity, scalable with input sizeRequires extra space for hash map
Fixed-size Array (Optimized Hash Map)
O(n)O(n)O(n)O(1)O(1)O(1) (constant space since array size is fixed at 26 for lowercase letters only)Most efficient in terms of both time and space complexity for this specific problem constraint (only lowercase English letters allowed)⚠️ Only works when the character set is known and limited

The optimal approach for this problem is Solution 5: Fixed-size Array (Optimized Hash Map), which achieves O(n)O(n)O(n) time complexity and O(1)O(1)O(1) space complexity. This approach is most suitable when dealing with strings that contain only lowercase English letters, as it leverages a fixed-size array of 26 elements to count character frequencies efficiently.


Previous238. Product of Array Except Self
Next283. Move Zeroes
Related posts
  • 49. Group AnagramsMedium
  • 13. Roman to IntegerEasy
  • 217. Contains DuplicateEasy
  • 347. Top K Frequent ElementsMedium
  • 1. Two SumEasy
On this page
15 lines
1class Solution:
2 def isAnagram(self, s: str, t: str) -> bool:
3 if len(s) != len(t):
4 return False
5
6 t_list = list(t)
7
8 for char in s:
9 # Check if the character from s is in t_list. If it is, remove it from t_list. If it is not, return False.
10 if char in t_list:
11 t_list.remove(char)
12 else:
13 return False
14
15 return True
7 lines
1class Solution:
2 def isAnagram(self, s: str, t: str) -> bool:
3 if len(s) != len(t):
4 return False
5
6 # Sort both strings and compare them
7 return sorted(s) == sorted(t)
13 lines
1class Solution:
2 def isAnagram(self, s: str, t: str) -> bool:
3 if len(s) != len(t):
4 return False
5
6 s_count, t_count = {}, {}
7
8 # Count the frequency of each character in both strings
9 for i in range(len(s)):
10 s_count[s[i]] = s_count.get(s[i], 0) + 1
11 t_count[t[i]] = t_count.get(t[i], 0) + 1
12
13 return s_count == t_count
11 lines
1class Solution:
2 def isAnagram(self, s: str, t: str) -> bool:
3 if len(s) != len(t):
4 return False
5
6 # Check if the frequency of each character in `s` matches the frequency in `t`
7 for char in set(s):
8 if s.count(char) != t.count(char):
9 return False
10
11 return True
18 lines
1class Solution:
2 def isAnagram(self, s: str, t: str) -> bool:
3 if len(s) != len(t):
4 return False
5
6 counts = [0] * 26 # Assuming only lowercase English letters
7
8 for i in range(len(s)):
9 counts[ord(s[i]) - ord('a')] += 1
10 counts[ord(t[i]) - ord('a')] -= 1
11
12 # Check if all counts are zero - can replace with all(count == 0 for count in counts)
13 # If any count is not zero, it means the two strings are not anagrams
14 for count in counts:
15 if count != 0:
16 return False
17
18 return True