top of page
  • LinkedIn
  • Facebook
  • YouTube
  • Twitter
  • Instagram
  • Pinterest
  • Tumblr
  • Vkontakte

Two Sum - Leetcode #1 Short & Simple Solution

Updated: Jun 17, 2022

Problem Statement

This is another article in the series leetcode problem solutions and this article is a solution to leetcode 1 two sum problem.

Once you have a good understanding of two sum problem, it should help you solve advanced level problems like three sum which in some ways a continuation of the two sum problem.

Consider you are given an array of integers and a target sum, return indices of two numbers in the array such that they add up to the given target. You may assume that each input would have exactly one solution. Also, you cannot use the same element twice. You are allowed to return the answer in any order.


Example 1:

Input: nums = [7,2,13,11], target = 9
Output: [0,1]

Example 2:

Input: nums = [7,3,5], target = 8
Output: [1,2]


Let us try to understand the problem statement first. Here we are given an array of integer elements and a target sum. Our job is to write an algorithm which returns indices of two elements in this array such that, when we add these two elements it should be equal to the target sum given.

For instance, in example 1 [7,2,13,11] is the given array and the given target sum = 9. If we take a look at the given array, the pair which adds to the target sum 9 is (7,2) i.e. 7+2 = 9. So our algorithm should return (0,1) as the result because these are the indexes of elements 7 and 2 respectively in the given array.