Ransom Note
LeetCode 383 | Difficulty: Easyβ
EasyProblem Descriptionβ
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 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
- `1 <= ransomNote.length, magazine.length <= 10^5`
- `ransomNote` and `magazine` consist of lowercase English letters.
Topics: Hash Table, String, Counting
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 116 ms)β
| Metric | Value |
|---|---|
| Runtime | 116 ms |
| Memory | N/A |
| Date | 2018-04-05 |
public class Solution {
public bool CanConstruct(string ransomNote, string magazine) {
Dictionary<char,int> mag = new Dictionary<char, int>();
for (int i = 0; i < magazine.Length; i++)
{
if(mag.ContainsKey(magazine[i]))
{
mag[magazine[i]]++;
}
else
{
mag.Add(magazine[i],1);
}
}
for (int i = 0; i < ransomNote.Length; i++)
{
if(mag.ContainsKey(ransomNote[i]))
{
if(mag[ransomNote[i]]<=0)
{
return false;
}
else
{
mag[ransomNote[i]]--;
}
}
else
{
return false;
}
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Hash map gives O(1) lookup β think about what to use as key vs value.