Sitemap
THEBUG

Learn to code, the weird way!

Two Sum

2 min readJan 5, 2022

--

Press enter or click to view image in full size

Today we discuss the infamous interview question — Two Sum - If you are prepping for an technical interview or just grinding leetcode or hackerrank or just trying to kill time casually browsing trough a CS book, you probably have stumbled upon this quesiton.

It usually is phrased something like —

Given an array of numbers and an target value, find out where the sum of the two numbers exist within the array.

At first glance, the question seems pretty easy, just go through the array and find out the two numbers. Right? Well, yes and no, if you are trying to crack a technical interview this answer might not get you the results you are trying to get. There is a much more efficient way of doing it within O(n) time. And that is what we will discuss in this article.

The logic behind this O(n) approach is that if you substract the target from an element from the array, the result is also within the array, you have your answer. Lets use an example —

Get THEBUG’s stories in your inbox

Join Medium for free to get updates from this writer.

[1,2,3,4,5] — Lets say we have this array, and the target we are trying to find is 6. We can see that 2 and 4 within the array and they add up to a 6. Using this logic, if we take the target — 6 and subtract it with 2, it leaves us with 4, and we know (using the dictionary) that 4 is at the 3rd index of the array.

First we define the dictionary, and populate it with the index number of each of the elements—

dictionary = {}
for i in range(len(nums)):
dictionary[nums[i]] = i

Then we once again iterate over the list/array, subtract each number with the target and use .get() to see if the result of the subtraction exists within the dicitonary. Also, we need to make sure we arent using the same element twice to create the result — For instance, in case of this array — [1,2,3,4,5], you can use 3 twice to make a 6, but that is not what we want to do here, which is why we use the dictionary to check if the index of the subtraction result not the same as the index we are on using —

i!=dictionary[target-nums[i]]

And here is the full code —Enjoy!

--

--