Back to photostream

Two Sum Leetcode Solution

In this problem, we have to find a pair of two distinct indices in a sorted array that their values add up to a given target. We can assume that the array has only one pair of integers that add up to the target sum. Note that the array is sorted in a non-decreasing manner.

Example

Array = {1 , 2 , 3 , 4 , 5}

Target = 6

1 5

Array = {1 , 4 , 5 , 11 , 12}

Target = 9

2 3

Approach(Brute Force)

This approach is straightforward. We can check for every pair in the array and if their sum is equal to the given target, print their indices. This kind of Brute Force solution needs to check every possible pair and number of possible pairs in the array = n * (n - 1) / 2. So, in the worst-case, this approach can be slow.

Algorithm

 

- Run a loop to maintain the first index of the solution in the array

- Run another loop to maintain a second index of the solution for every first integer

- If at any point, the sum of values of two indices is equal to the target

 

- Print its indices

 

Implementation of Two Sum Leetcode Solution

C++ Program

#include

using namespace std;

 

vector targetSum(vector &a , int &target)

{

int n = a.size();

for(int i = 0 ; i < n - 1 ; i++)

for(int j = i + 1 ; j < n ; j++)

{

if(a + a == target)

return {i + 1 , j + 1};

}

return {};

}

 

int main()

{

vector a = {1 , 4 , 5 , 11 , 12};

int target = 9;

for(int &x : targetSum(a , target))

cout

 

www.tutorialcup.com/leetcode-solutions/two-sum-leetcode-s...

18 views
0 faves
0 comments
Uploaded on October 20, 2021