Hash Tables: Ransom Note


Problem Statement :


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 cannot use 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 No.

Function Description

Complete the checkMagazine function in the editor below. It must print Yes if the note can be formed using the magazine, or No

Input Format

The first line contains two space-separated integers m, and n , the numbers of words in the and the magazine and the note.
The second line contains m space-separated strings, each magazine[i].
The third line contains n space-separated strings, each note[i]. 

Constraints

1 <= m,  n <= 300
1 <= | magazine[i] | , | note[i] | <= 5

.
Each word consists of English alphabetic letters (i.e, a to z and A to Z).

.Output Format

Print Yes if he can use the magazine to create an untraceable replica of his ransom note. Otherwise, print No.

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

.



Solution :



title-img


                            Solution in C :

In C :


#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define DICT_SIZE 50007

typedef struct _dict_entry
{
	uint64_t hash;
	char *str;
	int value;
} *dict_entry;

dict_entry dict[DICT_SIZE];

uint64_t get_hash(char *s)
{
	int shift = 0;

	uint64_t hash = 0;
	while (*s != '\0')
	{
		hash |= *s << shift;
		shift += 7;
		++s;
	}

	return hash;
}

dict_entry dict_get(char *s)
{
	uint64_t hash = get_hash(s);
	size_t pos = hash % DICT_SIZE;
	while (dict[pos] != NULL && dict[pos]->hash != hash)
		pos = (pos + 1) % DICT_SIZE;
	return dict[pos];
}

void dict_inc(char *s)
{
	dict_entry entry = dict_get(s);

	if (entry)
	{
		entry->value += 1;
	}
	else
	{
		entry = (dict_entry)malloc(sizeof(struct _dict_entry));
		memset(entry, 0, sizeof(struct _dict_entry));

		entry->hash = get_hash(s);
		entry->str = strdup(s);
		entry->value = 1;

		size_t pos = entry->hash % DICT_SIZE;
		while (dict[pos] != NULL)
			pos = (pos + 1) % DICT_SIZE;
		dict[pos] = entry;
	}
}

int is_doable()
{
	for (int j = 0; j < DICT_SIZE; ++j)
		if (dict[j] && dict[j]->value < 0)
			return 0;
	return 1;
}

int solve(int n)
{
	char buffer[10];

	for (int j = 0; j < n; ++j)
	{
		scanf("%s", buffer);

		dict_entry entry = dict_get(buffer);
		if (entry == NULL)
			return 0; // unbek. wort

		entry->value--;
	}

	return is_doable();
}

int main()
{
#ifdef _DEBUG
	char FNAME[250];
	strcpy(FNAME, __FILE__);
	strcpy(strchr(FNAME, '.'), ".txt");
	freopen(FNAME, "rt", stdin);
#endif

	int m, n;
	scanf("%d %d", &m, &n);

	char buffer[10];

	for (int j = 0; j < m; ++j)
	{
		scanf("%s", buffer);
		dict_inc(buffer);
	}

	printf(solve(n) ? "Yes" : "No");
}
                        


                        Solution in C++ :

In C++ :


#include <string>
#include <iostream>
#include <unordered_set>

using namespace std;

unordered_multiset<string> magazine, ransom;

int main()
{
    size_t N, M;
    cin >> N >> M;
    
    if(N < M)
    {
        cout << "No";
        return 0;
    }
    
    string str;
    
    for(size_t i = 0; i < N; ++i)
    {
        cin >> str;
        magazine.insert(str);
    }
    
    for(size_t i = 0; i < M; ++i)
    {
        cin >> str;
        ransom.insert(str);
    }
    
    for(const auto& word : ransom)
    {
        auto found = magazine.find(word);
        
        if(found == magazine.end())
        {
            cout << "No";
            return 0;
        }
        
        magazine.erase(found);
    }
    cout << "Yes";
}
                    


                        Solution in Java :

In java :


import java.util.*;

public class Solution {
    Map<String, Integer> magazineMap;
    Map<String, Integer> noteMap;
    
    public Solution(String magazine, String note) {
        this.noteMap = new HashMap<String, Integer>();
        this.magazineMap = new HashMap<String, Integer>();
        
       
        Integer occurrences;
        
        for(String s : magazine.split("[^a-zA-Z]+")) {
            occurrences = magazineMap.get(s);
            
            if(occurrences == null) {
                magazineMap.put(s, 1);
            }
            else {
                magazineMap.put(s, occurrences + 1);
            }
        }
        
        for(String s : note.split("[^a-zA-Z]+")) {
            occurrences = noteMap.get(s);
            
            if(occurrences == null) {
                noteMap.put(s, 1);
            }
            else {
                noteMap.put(s, occurrences + 1);
            }
        }
        
    }
    
    public void solve() {
        boolean canReplicate = true;
        for(String s : noteMap.keySet()) {
      if(!magazineMap.containsKey(s) || (magazineMap.get(s) < noteMap.get(s)) ) {
                canReplicate = false;
                break;
            }
        }
        
        System.out.println( (canReplicate) ? "Yes" : "No" );
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        
        // Eat whitespace to beginning of next line
        scanner.nextLine();
        
        Solution s = new Solution(scanner.nextLine(), scanner.nextLine());
        scanner.close();
        
        s.solve();
    }
}
                    


                        Solution in Python : 
                            
In Python3 :


def ransom_note(magazine, ransom):
    rc = {} # dict of word: count of that word in the note
    for word in ransom:
        if word not in rc:
            rc[word] = 0
        rc[word] += 1
    
    for word in magazine:
        if word in rc:
            rc[word] -= 1
            if rc[word] == 0:
                del rc[word]
                if not rc:
                    return True
    return False
        
    

m, n = map(int, input().strip().split(' '))
magazine = input().strip().split(' ')
ransom = input().strip().split(' ')
answer = ransom_note(magazine, ransom)
if(answer):
    print("Yes")
else:
    print("No")
                    


View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →