LeetCode #242. Valid Anagram

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, …


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » LeetCode #242. Valid Anagram." Giuseppe | Sciencx - Tuesday August 19, 2025, https://www.scien.cx/2025/08/19/leetcode-242-valid-anagram/
HARVARD
Giuseppe | Sciencx Tuesday August 19, 2025 » LeetCode #242. Valid Anagram., viewed ,<https://www.scien.cx/2025/08/19/leetcode-242-valid-anagram/>
VANCOUVER
Giuseppe | Sciencx - » LeetCode #242. Valid Anagram. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/08/19/leetcode-242-valid-anagram/
CHICAGO
" » LeetCode #242. Valid Anagram." Giuseppe | Sciencx - Accessed . https://www.scien.cx/2025/08/19/leetcode-242-valid-anagram/
IEEE
" » LeetCode #242. Valid Anagram." Giuseppe | Sciencx [Online]. Available: https://www.scien.cx/2025/08/19/leetcode-242-valid-anagram/. [Accessed: ]
rf:citation
» LeetCode #242. Valid Anagram | Giuseppe | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.