#383
Easy Algorithms Ransom note
Hash Table String Counting
65.7% acceptance
Jan 12, 2026
5641
543
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn can_construct(ransom_note: String, magazine: String) -> bool {
let mut counts = [0; 26];
for b in magazine.bytes() {
counts[(b - b'a') as usize] += 1;
}
for b in ransom_note.bytes() {
let idx = (b - b'a') as usize;
if counts[idx] == 0 {
return false;
}
counts[idx] -= 1;
}
true
}
}