This content originally appeared on DEV Community and was authored by Giuseppe
Time Complexity O(n);
Space Complexity O(k) where k ≤ n, worst case O(n)
Number of map entries = number of unique characters = k
k can range from 1 to n
Space complexity: O(k) where k ≤ n
So while all n characters are processed, you only store the unique ones with their counts.
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> mapS = new HashMap<>();
for (char c : s.toCharArray()) {
mapS.put(c, mapS.getOrDefault(c, 0) +1);
}
Map<Character, Integer> mapT = new HashMap<>();
for (char c : t.toCharArray()) {
mapT.put(c, mapT.getOrDefault(c, 0) +1);
}
return mapT.equals(mapS);
}
}
This content originally appeared on DEV Community and was authored by Giuseppe

Giuseppe | Sciencx (2025-08-19T10:49:34+00:00) LeetCode #242. Valid Anagram. Retrieved from https://www.scien.cx/2025/08/19/leetcode-242-valid-anagram/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.