Member-only story
Solving LeetCode #1 Two Sum Using Javascript In O(n)
In this article I’ll walk you through the logic and code of how to solve Leet Codes first and most common algorithm question, Two Sum. First lets break down the problem
The Problem
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
When deciding what approach you want to take to an algorithms problem its important to understand what you need to see at bare minimum. In this case we need to find out if any combination of two numbers in the given array add up to the target. So given an array of [1, 2, 11, 7] and a target of 9 we would need to visit all indices of the array since there is no other way of finding out that 2 and 7 exist in the array.
Crafting A Solution
Now that we’ve established that we need to visit every element the next step would be to decide what the best data structure is to do that. A for loop is great for traversing arrays since arrays have a defined length that you can loop through. So…