EasyNo. 0383
Ransom Note — LeetCode 383 Python Solution
- Pattern
- Hash Map
- Topics
- Hash Table, String, Counting
- On study lists
- Grind 75 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. Each letter in magazine can only be used once in ransomNote.
Example
- Input
- ransomNote = "a", magazine = "b"
- Output
- false
Python solution
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
cnt = Counter(magazine)
for c in ransomNote:
cnt[c] -= 1
if cnt[c] < 0:
return False
return TrueComplexity
- Time
- O(m + n)
- Space · auxiliary
- O(C)
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 383. Ransom Note is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0387 | First Unique Character in a String | Easy |
| 0299 | Bulls and Cows | Medium |
| 0451 | Sort Characters By Frequency | Medium |
| 0692 | Top K Frequent Words | Medium |
| 0767 | Reorganize String | Medium |
| 0811 | Subdomain Visit Count | Medium |
Frequently asked questions
- How hard is LeetCode 383. Ransom Note?
LeetCode 383. Ransom Note is rated Easy on LeetCode.
- What is the time complexity of LeetCode 383. Ransom Note?
The Python solution on this page runs in O(m + n).
- What is the space complexity of LeetCode 383. Ransom Note?
The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 383. Ransom Note cover?
LeetCode 383. Ransom Note is tagged Hash Table, String and Counting on LeetCode.