Cracking The Coding Interview:Two Sum problem python solution.

Celine Surai
2 min readMay 5, 2020

Given an array of integers, return indices of two numbers that add to a specific target.

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

Fore example:

Given nums = [2, 8, 12, 15], target = 20,Because nums [1] + nums [2] = 8 + 12= 20,
return [1, 2]

This here is a leetcode interview question and there are multiple ways of approaching this problem.

Unto the solution!

Solution 1: Brute Force solution

This is what many people would come up with after looking at the problem.

Whereby you would iterate the entire list and compare the numbers with every other number in the list and check whether they add up to the target.

Here is the code:

two sum bruteforce solution

However the problem with this solution is that it has a runtime of O(n²) whereby if the two numbers you are searching for are at the end of the list, you would need to go through all of the numbers multiple times, and in a scenario where you have large numbers this could actually be problematic.

In an interview setting this might not be the best way to approach this problem.

--

--

Celine Surai
Celine Surai

Written by Celine Surai

Software engineer. I write about my journey, Machine Learning, Web application development and also Python!

No responses yet