Find Pair With Given Sum in an Array

Given an array of integers and a value, determine if there are any two integers in the array whose sum is equal to the given value.

Statement

We’re given an array of integers and a value. Determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists; otherwise, return false.

Example

Consider this array and the target sums:

g d2 5 7 1 2 8 4 3 d Target Sum 10 7 + 3 = 10, 2 + 8 = 10 Target Sum 19 No 2 values sum upto 19

Sample input

This challenge covers both sorted and unsorted arrays.

[5, 7, 1, 2, 8, 4, 3] 
val = 3

Expected output

True

Try it yourself

The test cases include both sorted and unsorted arrays.

#include <iostream>
#include <vector>
using namespace std;
bool FindSumOfTwo(vector<int>& nums, int val) {
//TODO: Write - Your - Code
return false;
}

Solution 1

In this solution, we’ll use the following algorithm to find a pair that adds to the target (say val).

  • Scan the whole array once and store visited elements in a hash set.
  • During the scan, for every element e in the array, we check if val - e is present in the hash set. In other
...

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.