LeetCode #242 - Valid Anagram

NeetCode - Arrays & Hashing

ยท

2 min read

Problem

Link to the LeetCode problem: https://leetcode.com/problems/valid-anagram/.

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

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

Example 2:

Input: s = "rat", t = "car"
Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 10^4

  • s and t consist of lowercase English letters.


Solution

If two words are anagrams of each other then every single letter occurs the same number of times in both. Knowing this, we only have to count these occurrences in both words and determine whether they are equal or not.

For storing the letter counters we use two dictionaries: one for each word. The letters will be the keys and the number of occurrences will be the values. We count by going through each letter of both words - after making sure they are equal in length (otherwise, they can't be anagrams) - and incrementing the counters of the corresponding letters by one. Finally, we check whether the two dictionaries are equal or not.

def isAnagram(self, s: str, t: str) -> bool:
    if len(s) != len(t):
        return False

    sDict = defaultdict(int)
    tDict = defaultdict(int)

    for i in range(len(s)):
        sDict[s[i]] += 1
        tDict[t[i]] += 1

    return sDict == tDict

Notes

Python defaultdict-s are just like normal dict-s with the only difference that they never raise a KeyError. Instead, when not finding the provided key, they insert it with a default value. This default value comes from the default_factory parameter passed to the constructor.

Space complexity

Since we use two dictionaries for storing the letter occurrences the required space is determined by the lengths of the two words, thus ๐’ช(s.length + t.length).

Time complexity

Inside the loop, we search in and insert into the dictionaries, which are ๐’ช(1) operations. This is ๐’ช(n) * ( ๐’ช(1) * 4 ) so far, where n = max(s.length, t.length). Then we compare the two dictionaries in ๐’ช(26) time. (The 26 English letters mean at most 26 counters to compare.) This leads us to ๐’ช(n) * ( ๐’ช(1) * 4 ) + ๐’ช(26) which is ๐’ช(n).

ย