codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Member-only story

Understanding the Two Sum Problem

Matthew Henschke
codeburst
Published in
5 min readSep 30, 2020

One popular interview question that may or may not be thrown at you in a technical interview is known as the “Two Sum Problem”. For example, the Two Sum has been known for appearing on Facebook and Google interviews, and was the first Leetcode problem that I successfully solved with all test cases passed. Moreover, my relentless technical interview prep journey began with Two Sum!

The Two Sum Problem can be considered a Leetcode classic that consists of different fundamental solutions. Constructing these solutions involves an understanding of different techniques that will be discussed further below. Before continuing, I would absolutely recommend that you brush up on arrays, hash maps, time-complexity, and space-complexity in order to fully understand the problem. GeeksForGeeks has well-written articles on different interview problems and concepts and is a great resource for this. Let’s now dive into this problem.

Problem Description: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

It is important to note that you CANNOT use the same element in the array twice, but you can assume that there will only be ONE solution for each test case.

Example Test Cases

Input: nums = [1,4,10,-3], target = 14 
Output: [1,2] or [2,1] # 4 + 10 = 14
Input: nums = [9,5,1,23], target = 10
Output: [0,2] or [2,0] # 9 + 1 = 10
Input: nums = [1,-2,5,10], target = -1
Output: [0,1] or [1,0] # 1 + -2 = -1

As you can see from the test cases above, the output returned in each test case is an array of the indices of the two numbers that add up to the target. Note that the order of the indices that are in the solution array is not important for this problem. Now, let’s take a look at the different solutions of the Two Sum Problem using the Python3 programming language.

First Approach

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Matthew Henschke

A software engineer @ IBM with an immense passion for full-stack development!

Responses (3)

Write a response