LeetCode 383: Ransom Note is an Easy hashmap problem. This Python walkthrough develops a frequency consumption solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Easy |
|---|---|
| Topic | Hashmap |
| Reusable pattern | frequency consumption |
| Complexity | O(n+m) time and O(k) space |
Recognizing the pattern
A hash table converts a repeated search for prior information into an average constant-time lookup.
For this problem specifically, count available magazine characters and decrement for every requested character, failing when a count is exhausted. The invariant worth writing beside the code is: Counts represent unused magazine characters after satisfying the processed prefix.
Step-by-step algorithm
- Identify the input state consumed by
canConstruct(ransomNote, magazine)and initialize the data required by the frequency consumption pattern. - Count available magazine characters and decrement for every requested character, failing when a count is exhausted.
- After each update, verify the page’s central invariant: Counts represent unused magazine characters after satisfying the processed prefix.
- Finish only after the boundary behavior is covered: Repeated requested letters require separate available copies.
Python solution
from collections import Counter
class Solution:
def canConstruct(self, ransomNote, magazine):
available = Counter(magazine)
for char in ransomNote:
available[char] -= 1
if available[char] < 0: return False
return TrueReading the implementation
The main entry point is canConstruct(ransomNote, magazine). The named working state includes available; those variables make the frequency consumption state visible instead of hiding it in incidental control flow.
A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, count available magazine characters and decrement for every requested character, failing when a count is exhausted.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Count available magazine characters and decrement for every requested character, failing when a count is exhausted. Each update records the current item without invalidating earlier decisions; consequently, counts represent unused magazine characters after satisfying the processed prefix.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(n+m) time and O(k) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Sorting may reduce implementation state and reveal ordering, but it can lose original positions and normally costs O(n log n). That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().canConstruct("aa","aab")Common mistakes and edge cases
- Problem-specific boundary: Repeated requested letters require separate available copies.
- Pattern-level pitfall: Choose whether to look up before inserting: inserting too early can accidentally match an element with itself.
- Invariant check: after every update, confirm that counts represent unused magazine characters after satisfying the processed prefix.
Interview review checklist
- Explain why frequency consumption matches the structure of this input.
- State the invariant in one sentence before tracing code: Counts represent unused magazine characters after satisfying the processed prefix.
- Derive O(n+m) time and O(k) space from how many times each element or state is visited.
- Test the boundary explicitly: Repeated requested letters require separate available copies.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 289. Game of Life · Next: 205. Isomorphic Strings