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:
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 - Codereturn 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 ifval
-e
is present in the hash set. In other
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.