↓Skip to main content
  1. LeetCode/

LeetCode 383: Ransom Note

·1 min· ·
LeetCode Easy Hash-Table String Counting
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-23

  • Submissions: Wrong Answer → Accepted ×3

Approach
#

Count magazine’s characters (Hash Table Template 1) and subtract what ransomNote needs; any shortfall fails. Python’s Counter(a) - Counter(b) keeps only positive counts, so an empty result means every character suffices.

My Attempts
#

Attempt 1 returned bool(Counter(ransomNote) - Counter(magazine)), the exact opposite: a non-empty difference means a shortfall, so "a", "c" returned True. Using not passed.

Solution
#

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        return not (Counter(ransomNote) - Counter(magazine))

Complexity
#

Time O(n + m), space O(k).

Mistakes to Avoid
#

  • A non-empty difference means a shortfall, so return not ..., not bool(...).

Interview Explanation
#

I subtract magazine’s counts from ransomNote’s; Counter subtraction keeps only positives, so an empty result means everything is covered. Time O(n + m).

Related

LeetCode 387: First Unique Character in a String
·1 min
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 note: count first, then scan left to right for the first character with count 1
LeetCode 290: Word Pattern
·1 min
LeetCode Easy Hash-Table String
LeetCode 290 note: pattern characters and words must correspond one to one; use two dicts or compare set sizes
LeetCode 389: Find the Difference
·1 min
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 note: t has one extra character; XOR every character of both strings, pairs cancel, and the extra one remains
LeetCode 409: Longest Palindrome
·2 mins
LeetCode Easy Hash-Table String Greedy
LeetCode 409 note: use an even number of each character on the two sides, plus one in the middle if any count is odd
LeetCode 242: Valid Anagram
·2 mins
LeetCode Easy Hash-Table String Sorting
LeetCode 242 note: two strings are anagrams exactly when their character counts match; compare Counters or sorted strings
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