Skip to content

Commit 6acdfa0

Browse files
committed
added ransomNote solution to easy folder
1 parent 099e926 commit 6acdfa0

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Easy/ransomNote.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Given an arbitrary ransom note string and another string containing letters from all the magazines,
2+
// write a function that will return true if the ransom note can be constructed from the magazines;
3+
// otherwise, it will return false.
4+
5+
// Each letter in the magazine string can only be used once in your ransom note.
6+
7+
// Note:
8+
// You may assume that both strings contain only lowercase letters.
9+
// canConstruct("a", "b") -> false
10+
// canConstruct("aa", "ab") -> false
11+
// canConstruct("aa", "aab") -> true
12+
13+
const canConstruct = function(ransomNote, magazine) {
14+
const magazineMap = {};
15+
16+
for (const char of magazine) {
17+
if (magazineMap[char]) {
18+
magazineMap[char]++;
19+
} else {
20+
magazineMap[char] = 1;
21+
}
22+
}
23+
24+
for (const char of ransomNote) {
25+
if (magazineMap[char] > 0) {
26+
magazineMap[char]--;
27+
continue;
28+
}
29+
return false;
30+
}
31+
return true;
32+
};
33+
34+
console.log(canConstruct("a", "b")) // -> false
35+
console.log(canConstruct("aa", "ab")) // -> false
36+
console.log(canConstruct("aa", "aab")) // -> true

0 commit comments

Comments
 (0)