Hash Tables: Ransom Note
Check out the resources on the page's right side to learn more about hashing. The video tutorial is by Gayle Laakmann McDowell, author of the best-selling interview book Cracking the Coding Interview.
Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannotuse substrings or concatenation to create the words he needs.
Given the words in the magazine and the words in the ransom note, print Yes
if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No
.
For example, the note is "Attack at dawn". The magazine contains only "attack at dawn". The magazine has all the right words, but there's a case mismatch. The answer is .
Function Description
Complete the checkMagazine function in the editor below. It must print if the note can be formed using the magazine, or .
checkMagazine has the following parameters:
- magazine: an array of strings, each a word in the magazine
- note: an array of strings, each a word in the ransom note
Input Format
The first line contains two space-separated integers, and , the numbers of words in the and the ..
The second line contains space-separated strings, each .
The third line contains space-separated strings, each .
Constraints
- .
- Each word consists of English alphabetic letters (i.e., to and to ).
Output Format
Print Yes
if he can use the magazine to create an untraceable replica of his ransom note. Otherwise, print No
.
Sample Input 0
6 4
give me one grand today night
give one grand today
Sample Output 0
Yes
Sample Input 1
6 5
two times three is not four
two times two is four
Sample Output 1
No
Explanation 1
'two' only occurs once in the magazine.
Sample Input 2
7 4
ive got a lovely bunch of coconuts
ive got some coconuts
Sample Output 2
No
Explanation 2
Harold's magazine is missing the word .
이 문제의 레벨은 easy이다. 그럼에도 보이는 그대로 일단 구현을 해보면, 결국 타임아웃이 발생한다.
HackerRank에 있는 문제는 쓸데없이 루프를 돌면서 처리하는 로직을 상당히 싫어한다.
일단 처음에 문제를 보고 있는 그대로 풀어보았다. magazine과 note를 루프 돌면서 중복 처리를 제거하기 위해 조건에 만족하는 요소들은 그때 바로 삭제하여 전체적으로 처리할 갯수를 줄여가면서 처리하였다.
그런데, 이 로직에서도 타임아웃이 발생하였다.
결국 루프를 돌긴 돌되 직접 비교, 삭제를 하지 않고 각 요소별로 map을 구성하여 카운트를 비교하는 방식으로 변경하였다.
그랬더니, 타임아웃이 발생하지 않고 처리되었다.
하지만.............내가 보기엔 그게 그거 아닌가.........싶기도 하다.