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.
We'll cover the following...
We'll cover the following...
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
ein the array, we check ifval-eis present in the hash set. In other words, we check ifval-ewas already visited.