Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

HackerRank Hash Tables: Ransom Note problem solution

YASH PAL, 31 July 2024

In this HackerRank Hash Tables: Ransom Note Interview preparation kit problem solution you have 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.

HackerRank Hash Tables: Ransom Note solution

Problem solution in Python programming.

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the checkMagazine function below.
def checkMagazine(magazine, note):
    dict = {}
    for word in magazine:
        dict[word] = dict.get(word,0) + 1
    for word in note:
        if dict.get(word,0) == 0:
            print('No')
            return
        else:
            dict[word] -= 1
    print('Yes')

if __name__ == '__main__':
    mn = input().split()

    m = int(mn[0])

    n = int(mn[1])

    magazine = input().rstrip().split()

    note = input().rstrip().split()

    checkMagazine(magazine, note)

Problem solution in Java Programming.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        int n = in.nextInt();
        in.nextLine();
        String magazine[] = in.nextLine().split(" ");
        String note[] = in.nextLine().split(" ");
        HashMap<String,Integer> hm=new HashMap<String,Integer>();
        for(int i=0;i<m;i++){
            if(hm.containsKey(magazine[i])){
                hm.put(magazine[i],hm.get(magazine[i])+1);
            }
            else
                hm.put(magazine[i],1);
                
        }
        
        boolean check=false;
        for(int i=0;i<n;i++){
            if(!hm.containsKey(note[i]))
                check=true;
            else{
                if(hm.get(note[i])>1)
                    hm.put(note[i],hm.get(note[i])-1);
                else
                    hm.remove(note[i]);
            }
        }
        if(!check)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}

Problem solution in C++ programming.

#include<bits/stdc++.h>
using namespace std;
map<string,int> mp;

bool ransom_note(vector<string> magazine, vector<string> ransom) {
    
    //cout<<mp["a"]<<endl;
    
        for(int i=0;i<magazine.size();i++)
            mp[magazine[i]]++;
        
    //cout<<mp["give"]<<endl;
    for(int i=0;i<ransom.size();i++){
        if(mp[ransom[i]]==0)return false;
        else mp[ransom[i]]--;
    } 
        return true;
}

int main(){
    int m;
    int n;
    cin >> m >> n;
    vector<string> magazine(m);
    for(int magazine_i = 0;magazine_i < m;magazine_i++){
       cin >> magazine[magazine_i];
    }
    vector<string> ransom(n);
    for(int ransom_i = 0;ransom_i < n;ransom_i++){
       cin >> ransom[ransom_i];
    }
    if(ransom_note(magazine, ransom))
        cout << "Yesn";
    else
        cout << "Non";
    return 0;
}

Problem solution in C programming.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int m; 
    int n; 
    scanf("%d %d",&m,&n);
    char* *magazine = malloc(sizeof(char*) * m);
    for(int magazine_i = 0; magazine_i < m; magazine_i++){
       magazine[magazine_i] = (char *)malloc(6 * sizeof(char));
       scanf("%s",magazine[magazine_i]);
    }
    char* *ransom = malloc(sizeof(char*) * n);
    if (m==0 && n>0) {
        printf("Non");
        return 0;
    }

    for(int ransom_i = 0; ransom_i < n; ransom_i++){
        ransom[ransom_i] = (char *)malloc(6 * sizeof(char));
        scanf("%s",ransom[ransom_i]);
        int magazine_i;
        for(magazine_i = 0; magazine_i < m; magazine_i++){
            if(strcmp(magazine[magazine_i], ransom[ransom_i])==0) {
                magazine[magazine_i] = "";
                break;
            }
        }
        if(magazine_i >= m) {
          printf("Non");
          return 0;
        }
    }

    printf("Yesn");

    return 0;
}

Problem solution in JavaScript programming.

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var m_temp = readLine().split(' ');
    var m = parseInt(m_temp[0]);
    var n = parseInt(m_temp[1]);
    magazine = readLine().split(' ');
    ransom = readLine().split(' ');
    let tracker = {};
    for (let i = 0; i < magazine.length; i++) {
        if (!tracker[magazine[i]]) {
            tracker[magazine[i]] = 0;
        }
        tracker[magazine[i]]++;
    }
    for (let i = 0; i < ransom.length; i++) {
        if (tracker[ransom[i]]) {
            tracker[ransom[i]]--;
        } else {
            console.log('No');
            return;
        }
    }
    console.log('Yes');
}

coding problems solutions interview prepration kit

Post navigation

Previous post
Next post

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes