Logo
    Logo

    ©️ 2020-2026, Akhil Abraham.

    LinkedInGitHubMediumX
    Akhil Abraham
    Akhil Abraham
    /Posts
    Posts
    /LeetCode
    LeetCode
    /
    LeetCode
    /0242 - Valid Anagram
    0242 - Valid Anagram
    0242 - Valid Anagram
    0242 - Valid Anagram

    0242 - Valid Anagram

    Difficulty
    Easy
    Language
    Python
    URL
    https://leetcode.com/problems/valid-anagram/

    Solution 1 - Hash Map (Counter)

    Count the frequency of each character in both strings using a hash map. If both frequency maps are identical, the strings are anagrams. Return True if they match, False otherwise.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 2 - Manual Frequency Count

    Manually build a frequency dictionary for each string and compare them. This avoids importing Counter and demonstrates the underlying logic explicitly.

    TimeComplexity:O(n)TimeComplexity: O(n)TimeComplexity:O(n)
    SpaceComplexity:O(1)SpaceComplexity: O(1)SpaceComplexity:O(1)

    Solution 3 - Sorting

    Sort both strings and compare them directly. If the sorted versions are equal, the strings are anagrams.

    TimeComplexity:O(nlog⁡n)TimeComplexity: O(n \log n)TimeComplexity:O(nlogn)
    SpaceComplexity:O(n)SpaceComplexity: O(n)SpaceComplexity:O(n)
    """ 0242.1 - Valid Anagram - Solution 1 - Hash Map (Counter) """
    
    #####################################################################################
    # Imports
    #####################################################################################
    from collections import Counter
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def isAnagram(self, s: str, t: str) -> bool:
            """Valid Anagram Function"""
            if len(s) != len(t):
                return False
    
            return Counter(s) == Counter(t)
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().isAnagram("anagram", "nagaram"))  # True
        print(Solution().isAnagram("rat", "car"))          # False
        print(Solution().isAnagram("a", "ab"))             # False
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 0242.2 - Valid Anagram - Solution 2 - Manual Frequency Count """
    
    #####################################################################################
    # Imports
    #####################################################################################
    
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def isAnagram(self, s: str, t: str) -> bool:
            """Valid Anagram Function"""
            if len(s) != len(t):
                return False
    
            count_s = {}
            count_t = {}
    
            for i in range(len(s)):
                count_s[s[i]] = count_s.get(s[i], 0) + 1
                count_t[t[i]] = count_t.get(t[i], 0) + 1
    
            return count_s == count_t
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().isAnagram("anagram", "nagaram"))  # True
        print(Solution().isAnagram("rat", "car"))          # False
        print(Solution().isAnagram("a", "ab"))             # False
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()
    
    """ 0242.3 - Valid Anagram - Solution 3 - Sorting """
    
    #####################################################################################
    # Imports
    #####################################################################################
    
    
    #####################################################################################
    # Classes
    #####################################################################################
    class Solution:
        """Solution Class"""
    
        def isAnagram(self, s: str, t: str) -> bool:
            """Valid Anagram Function"""
            return sorted(s) == sorted(t)
    
    
    #####################################################################################
    # Functions
    #####################################################################################
    def testcase():
        """Test Function"""
        print(Solution().isAnagram("anagram", "nagaram"))  # True
        print(Solution().isAnagram("rat", "car"))          # False
        print(Solution().isAnagram("a", "ab"))             # False
    
    
    #####################################################################################
    # Main
    #####################################################################################
    if __name__ == "__main__":
        testcase()