diff --git a/src/solutions/ransom-note.ts b/src/solutions/ransom-note.ts index 59be360..b68cef4 100644 --- a/src/solutions/ransom-note.ts +++ b/src/solutions/ransom-note.ts @@ -1,5 +1,22 @@ -// O(n*m) +// O(n+m) export function canConstruct(ransomNote: string, magazine: string): boolean { - const needleIdx = magazine.indexOf(ransomNote); - return needleIdx !== -1; + const magazineMap = new Map(); + + for (const char of magazine) { + if (magazineMap.has(char)) { + magazineMap.set(char, magazineMap.get(char)! + 1); + } else { + magazineMap.set(char, 1); + } + } + + for (const char of ransomNote) { + if (magazineMap.get(char)) { + magazineMap.set(char, magazineMap.get(char)! - 1); + } else { + return false; + } + } + + return true; }