Problem Category:: Array, Hash table Neetcode Category:: Arrays and Hashing

https://leetcode.com/problems/valid-anagram/

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

Optimal

Dictionary (hash table)

Use a hash table based data structure, such as Dictionary. Store letter frequencies using the letter as the key

  • Increment for the first word and decrement for the second so that we can use just one dictionary
  • dictionary puts/edits, dictionary traversal → time complexity
  • space complexity

Others

Sort and compare

  • Time complexity:
    • Sort the characters in both strings:
    • Compare the two lists
  • Space complexity: (reducible to when using methods that avoid duplication)

Example

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
	    return sorted(s) == sorted(t) # O(n) space due to strings being immutable

Python sorted()

Unlike list.sort(), the sorted() function works on any iterable, including strings, so we don’t have to split

  • However, sorted() makes a copy, unlike list.sorted(). For our immutable strings, this is desired