Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Build confidence with an intuition-first walkthrough focused on hash map fundamentals.
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 <= 105ransomNote and magazine consist of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map
"a" "b"
"aa" "ab"
"aa" "aab"
stickers-to-spell-word)find-words-that-can-be-formed-by-characters)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #383: Ransom Note
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] cnt = new int[26];
for (int i = 0; i < magazine.length(); ++i) {
++cnt[magazine.charAt(i) - 'a'];
}
for (int i = 0; i < ransomNote.length(); ++i) {
if (--cnt[ransomNote.charAt(i) - 'a'] < 0) {
return false;
}
}
return true;
}
}
// Accepted solution for LeetCode #383: Ransom Note
func canConstruct(ransomNote string, magazine string) bool {
cnt := [26]int{}
for _, c := range magazine {
cnt[c-'a']++
}
for _, c := range ransomNote {
cnt[c-'a']--
if cnt[c-'a'] < 0 {
return false
}
}
return true
}
# Accepted solution for LeetCode #383: Ransom Note
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 True
// Accepted solution for LeetCode #383: Ransom Note
struct Solution;
use std::collections::HashMap;
impl Solution {
fn can_construct(ransom_note: String, magazine: String) -> bool {
let mut hm: HashMap<char, i32> = HashMap::new();
if ransom_note.len() > magazine.len() {
return false;
}
if ransom_note == magazine {
return true;
}
for c in magazine.chars() {
let e = hm.entry(c).or_default();
*e += 1;
}
for c in ransom_note.chars() {
if let Some(v) = hm.get_mut(&c) {
*v -= 1;
if *v < 0 {
return false;
}
} else {
return false;
}
}
true
}
}
#[test]
fn test() {
let r = "a".to_string();
let m = "b".to_string();
assert_eq!(Solution::can_construct(r, m), false);
let r = "aa".to_string();
let m = "ab".to_string();
assert_eq!(Solution::can_construct(r, m), false);
let r = "aa".to_string();
let m = "aab".to_string();
assert_eq!(Solution::can_construct(r, m), true);
}
// Accepted solution for LeetCode #383: Ransom Note
function canConstruct(ransomNote: string, magazine: string): boolean {
const cnt: number[] = Array(26).fill(0);
for (const c of magazine) {
++cnt[c.charCodeAt(0) - 97];
}
for (const c of ransomNote) {
if (--cnt[c.charCodeAt(0) - 97] < 0) {
return false;
}
}
return true;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan the rest of the array looking for a match. Two nested loops give n × (n−1)/2 comparisons = O(n²). No extra space since we only use loop indices.
One pass through the input, performing O(1) hash map lookups and insertions at each step. The hash map may store up to n entries in the worst case. This is the classic space-for-time tradeoff: O(n) extra memory eliminates an inner loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.