You are viewing a single comment's thread. Return to all comments →
Initially I went for the following naive implementation but I noticed it's slow:
function checkMagazine(magazine, note) { const missingWordIndex = note.find((word) => { const magazineWordIndex = magazine.indexOf(word); if (magazineWordIndex !== -1) { magazine.splice(magazineWordIndex, 1); return false; } return true; }); console.log(typeof missingWordIndex === 'undefined' ? 'Yes' : 'No'); }
but then I used maps:
const magazineMap = new Map(); for (let i in magazine) { const word = magazine[i]; let num = magazineMap.get(word); magazineMap.set(word, num ? num+1 : 1); } const noteMap = new Map(); for (let i in note) { const word = note[i]; let num = noteMap.get(word); noteMap.set(word, num ? num+1 : 1); } if (noteMap.size > magazineMap.size) { console.log('No'); return; } for (let [word, noteWordCount] of noteMap) { const magazineWordCount = magazineMap.get(word); if (!magazineWordCount || noteWordCount > magazineWordCount) { console.log('No'); return; } } console.log('Yes'); }
Seems like cookies are disabled on this browser, please enable them to open this website
Hash Tables: Ransom Note
You are viewing a single comment's thread. Return to all comments →
Initially I went for the following naive implementation but I noticed it's slow:
but then I used maps: