Using Hash Maps in Algorithmic Problems

Last week, I touched up on a few essential hash map methods. This week, I’ll be going through a LeetCode algorithm problem that I worked on in which I implemented a hash map.

Two Sum is an easy-level algorithm problem with the following prompt:

“Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.”

They provided a number of examples, but here is the first example:

As shown here, I utilized a hash map and a for loop. I started off by initializing a map. Then, I use a for loop to go through each number in the given nums array. In the loop, I either look for the complement number or add a new value into the map. As it goes through each value of the array, it searches for the complementing number that will add up to the given target value.

As this is just an easy-level problem, the use of a hash map was simple and easy to follow. However, as I approach more higher-difficulty problems that utilizes a hash map, I’ll update and add on to this post!

--

--

Software Engineer | Flatiron School Alum | Dancer | Looking for Work!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Esther 승연 Kang

Software Engineer | Flatiron School Alum | Dancer | Looking for Work!