This page looks best with JavaScript enabled

Valid Anagram

 ·  ☕ 2 min read  ·  ✍️ Syed Dawood

Problem

LeetCode 242: Valid Anagram

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # Solution 1
        if len(s) != len(t):
            return False
        for i in set(s):
            if s.count(i) != t.count(i):
                return False
        return True

    def isAnagram1(self, s: str, t: str) -> bool:
        # Solution 2
        if len(s) != len(t):
            return False
        dict_s, dict_t = {}, {}
        for i in range(len(s)):
            dict_s[s[i]] = dict_s.get(s[i], 0) + 1
            dict_t[t[i]] = dict_t.get(t[i], 0) + 1
        return dict_t == dict_s

    def isAnagram2(self, s: str, t: str) -> bool:
        # Solution 3
        from collections import Counter

        return Counter(s) == Counter(t)

Explaination

For two strings to be anagrams

  • They have to be the same length.
  • The composition of their alphabet is the same, but the order will vary.

Let me show you three ways to solve this problem. We construct two hashmaps/dictionaries where the value is the number of their appearances and the key is the alphabet. You compare the two dicts once you’ve constructed them.

It can also be solved with sets and the str.count method. To remove duplicates, you convert one of the strings to a set. Next, we compare the number of letters in each string. We have anagrams if everything matches.

There is a one line solution to this problem using collections.Counter.

Reference

Also see

Share on

ALLSYED
WRITTEN BY
Syed Dawood
< frontend | backend | fullstack > Developer