Skip to content

HackerRank Solutions – Hash Tables – Ransom Note – Java Solution

All credits to Rodney Shaghoulian for this simple solution for the HackerRank challenge – Hash Tables – Ransom Note. This solution is written in Java.

// Author: Rodney Shaghoulian
// Github: github.com/RodneyShag

/* Determines if ransom letter can be made from magazine */
public static void checkMagazine(String[] magazine, String[] ransom) {
    HashMap<String, Integer> usableWords = makeMap(magazine);
    for (int i = 0; i < ransom.length; i++) {
        if (usableWords.containsKey(ransom[i]) && usableWords.get(ransom[i]) > 0) {
            usableWords.merge(ransom[i], -1, Integer::sum); // uses the word
        } else {
            System.out.println("No");
            return;
        }
    }
    System.out.println("Yes");
}

/* Creates and returns a HashMap out of an array of Strings */
private static HashMap<String, Integer> makeMap(String[] words) {
    HashMap<String, Integer> map = new HashMap<>();
    for (int i = 0; i < words.length; i++) {
        map.merge(words[i], 1, Integer::sum);
    }
    return map;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.