Skip to main content

Hash Tables: Ransom Note HackerRank Solution | Java Solution

Java Solution for Hash Tables: Ransom Note HackerRank Problem

Hash Tables: Ransom Note HackerRank Solution in Java

Problem Description :-

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.

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 

See full description in HackerRank :-

Let's see solution :-

Solution 1 :-

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class HashTablesRansomNote {

    static void checkMagazine(String[] magazine, String[] note) {

        Map<String, Integer> map = new HashMap<>();
       
        // Put all note words into map and total occurrence
        for (String string : note) {
            if (!map.containsKey(string)) {
                map.put(string, 1);
            } else {
                map.put(string, (map.get(string)+1));
            }
        }
       
        // Remove founded word from map
        for (String string : magazine) {
            if (map.containsKey(string)) {
                map.put(string, (map.get(string)-1));
               
                if (map.get(string) == 0) {
                    map.remove(string);
                }
            }
        }
    
        // If map contains any value that means
        // some words are missing in magazine
        if (map.size() > 0) {
            System.out.println("No");
        } else {
            System.out.println("Yes");
        }
       
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String[] mn = scanner.nextLine().split(" ");

        int m = Integer.parseInt(mn[0]);

        int n = Integer.parseInt(mn[1]);

        String[] magazine = new String[m];

        String[] magazineItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < m; i++) {
            String magazineItem = magazineItems[i];
            magazine[i] = magazineItem;
        }

        String[] note = new String[n];

        String[] noteItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            String noteItem = noteItems[i];
            note[i] = noteItem;
        }

        checkMagazine(magazine, note);

        scanner.close();
    }

}

Explanation :-

  1. First we loop through note and put all words with words occurrence. key as word and value as total word occurrence.
  2. Loop through magazine and check if note's word is present in magazine array or not. if note's word found in magazine array then we delete that from map.
  3. Now last, if map contains any value in it that means magazine missing words that contains into note.

Solution 2 :- 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class HashTablesRansomNote {

    static void checkMagazine(String[] magazine, String[] note) {
       
        Arrays.sort(magazine);
        Arrays.sort(note);
       
        List<String> magazineList = new ArrayList<>();
        Collections.addAll(magazineList, magazine);
       
        List<String> noteList = new ArrayList<>();
        Collections.addAll(noteList, note);
       
        boolean flag = false;
        for (int i = 0; i < noteList.size(); i++) {
            if (magazineList.contains(note[i])) {
                magazineList.remove(note[i]);
                flag = true;
            } else {
                flag = false;
                break;
            }
        }
        System.out.println(flag ? "Yes" : "No");
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String[] mn = scanner.nextLine().split(" ");

        int m = Integer.parseInt(mn[0]);

        int n = Integer.parseInt(mn[1]);

        String[] magazine = new String[m];

        String[] magazineItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < m; i++) {
            String magazineItem = magazineItems[i];
            magazine[i] = magazineItem;
        }

        String[] note = new String[n];

        String[] noteItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i < n; i++) {
            String noteItem = noteItems[i];
            note[i] = noteItem;
        }

        checkMagazine(magazine, note);

        scanner.close();
    }

}

Explanation :-

  1. First we sort both arrays.
  2. Create two new ArrayList and store both arrays into them.
  3. We loop through Note List array and if magazine list contains note list word then we delete magazine array founded word. and set flag to true.
  4. if any word does not found in magazine then set flag as false and break the loop. no need to check after that.


If you have any query regarding to above code or explanation then comment down.

Other HackerRank problem and solutions :-

Spring boot Tutorials :-

 

 


Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...