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

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 ...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...