Repeat Code With LeetCode — Ransom Note

Hooray! Another easy LeetCode question that you can solve with a hashmap

Evan SooHoo
2 min readJun 14, 2024
Photo by Alex Shute on Unsplash

We’ve been down this road before, so let’s get it over with…

Ransom Note is an easy question on week two of Grind75, which was created by Yangshun Tay to be a new and improved version of his much more famous Blind75. Like many other hashmap questions, you can solve this by storing character counts. It’s slightly different than anagrams, but only slightly.

If you are not familiar with hashmaps, you can read about them here and this problem will be a fruitful learning experience. If you are already well-versed in hashmaps, then this problem is basically a rehash.

In “valid anagram,” you can use a hashmap to store character counts and then see if your hashmap is full of “0 values.” Similarly, in this problem you can do essentially the same thing, only your hashmap can have leftover values. Load it with character counts from the “magazine,” subtract values from your “ransom note,” and see if you are forced to dip below 0. If you are, at any point, then this is not valid.

The Problem

Ransom Note

Difficulty: Easy

Skills Required: Hashmaps

Description:

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

The Solution

This is not the best solution, per se, but it works. Another way to solve this is by creating an array of size 26, like this person had. I consider this fundamentally the same approach, but you can probably get higher scores with a “makeshift hashmap.”

We can leave the hashmap vs hash table nuance for another day.

Closing Thoughts

--

--

Evan SooHoo

A software engineer who writes about software engineering. Shocking, I know.