↓Skip to main content
  1. LeetCode/

LeetCode 242: Valid Anagram

·2 mins· ·
LeetCode Easy Hash-Table String Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-22

  • Submissions: Accepted ×3 → Runtime Error ×2 → Accepted → Runtime Error → Wrong Answer → Accepted → Wrong Answer ×4

Approach
#

Anagrams have identical character counts (Hash Table Template 1). Counter(s) == Counter(t) does it in one line; by hand, one dict gets +1 for each character of s and -1 for each of t, and every value must end at 0.

My Attempts
#

In 2022-08 both sorted and Counter passed; then I tried counting by hand:

  • tracker.get(x, 0) + 1 never stored the result, so the map stayed empty and all(...) on nothing is True: "a" and "c" returned True.

A 2022-11 rewrite failed four more times:

  • The second loop decremented alpha_count[s], where s was the leftover variable from the first loop rather than the current character t, and only the sum was checked, letting positives and negatives cancel: "ac" and "aa" returned True.
  • The last version used not all(values), meaning “some count is 0”: "ba" and "b" returned True.

Solution
#

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        cnt = defaultdict(int)
        for a, b in zip(s, t):
            cnt[a] += 1
            cnt[b] -= 1
        return all(v == 0 for v in cnt.values())

Complexity
#

Time O(n), space O(k) for k distinct characters.

Mistakes to Avoid
#

  • Check that every count is 0, not their sum: +1 and -1 cancel out.
  • tracker.get(x, 0) + 1 computes a value but never stores it.

Interview Explanation
#

One hash map adds one for each character of the first string and subtracts one for the second; if every count ends at zero, they are anagrams. Time O(n); with lowercase letters only, a size-26 array works.

Related

LeetCode 205: Isomorphic Strings
·2 mins
LeetCode Easy Hash-Table String
LeetCode 205 note: characters must map one to one; it holds when the distinct characters and distinct pairs all have the same count
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 169: Majority Element
·2 mins
LeetCode Easy Array Hash-Table Divide-and-Conquer Sorting
LeetCode 169 note: Boyer-Moore voting, where different values cancel in pairs and the survivor is the one appearing more than half the time
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 257: Binary Tree Paths
·1 min
LeetCode Easy String Backtracking Tree Depth-First-Search
LeetCode 257 note: DFS carrying the path string down, adding the whole path at each leaf
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)