So in preparation for interviews and keeping sharp mentally, I like to start off my day with a simple code challenge.
This week it was LeetCode: Two Sum
This problem is labeled easy, but intrigued me that it included a solution, so I thought I’d give it a go.
First, I always like to write down my approach like the following:
This is definitely not the best approach. I know that, but I always like to find a brute force approach to solving a problem because it can help when you’re really stumped and need to come up with something at all costs. In an idea world, that would never happen, but I think when you’ve had a long day and you’re wanting to finish what you’re working on, you should get it working if you can and come back to it in hopes of refactoring.
So this is what my first code submission looked like:
Ok, so a nested for loop isn’t very elegant, and most definitely not performant.
Let’s peak at their solution and see what’s up.
Woah. Aha! So this is a perfect opportunity to use a Hash Map. A Hash Map is a data structure used for storing Key & value pairs. JavaScript has an implementation of this, however, an object was used in my version of the solution.
Here’s what it looks like using a JS Object:
Next I will give it a try with JS’s version of Map and see if that speeds up the run time at all. The fastest I could get was 86ms in JS. Until next time!
Leave a Reply