Post

LC 242 - Valid Anagram

LC 242 - Valid Anagram

Question

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

Example 1:

1
2
Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

1
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?

Question here and solution here

Solution

concept

We use a hash map to keep track the char in each string, then we compare them afterwards.

code

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        char_dict = {}

        for c in s:
            if c in char_dict:
                char_dict[c] += 1
            else:
                char_dict[c] = 1

        for c in t:
            if c not in char_dict:
                return False
            else:
                char_dict[c] -= 1
                if char_dict[c] == 0:
                    del char_dict[c]

        return True if len(char_dict) == 0 else False

class NeetSolution1(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        lower space complexity since sometimes we assume sorting do not take up space.
        """
        return sorted(s) == sorted(t)
        
class NeetSolution2(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        space complexity: O(n) or O(s+t) -> stores hash table for s and t
        time complexity: O(n) or O(s+t) -> iterate through s and t
        """
        if len(s) != len(t):
            return False

        s_hash = {}
        t_hash = {}

        for i in range(len(s)):
            s_hash[s[i]] = s_hash.get(s[i], 0) + 1
            t_hash[t[i]] = t_hash.get(t[i], 0) + 1

        if s_hash == t_hash:
            return True
        else:
            return False

Complexity

time: $O(n)$ -> iterate through s and t
space: $O(n)$ -> stores hash table for s and t

This post is licensed under CC BY 4.0 by the author.