Keep and Share logo     Log In  |  Mobile View  |  Help  
 
Visiting
 
Select a Color
   
 












01.DS.02.09. Find Pair With Given Sum in an Array.html -- 1.8 meg
 Find Pair With Given Sum in an Array - Coderust: Hacking the Coding Interview
Log InJoin for free
Back To Module Home
Data Structures
0% completed
Further Reading
Mark Module as Completed
Ask a Question

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:

gd25712843dTarget Sum107 + 3 = 10, 2 + 8 = 10Target Sum19No 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.

C++
Java
Python
JS
Ruby
Go
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <vector>
using namespace std;
bool FindSumOfTwo(vector<int>& nums, int val) {
    //TODO: Write - Your - Code
    return false;
}
#
#include <iostream> #include <vector> using namespace std; bool FindSumOfTwo(vector<int>& nums, int val) { //TODO: Write - Your - Code return false; }
Enter to Rename, Shift+Enter to Preview
Test
Need Hint?
Save
Reset

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 words, we check if val - e was already visited.
    • If val - e is found in the hash set, it means there is a pair (e, val - e) in the array whose sum is equal to the given val, and the function returns true.
    • If we exhaust all elements in the array and don’t find any such pair, the function returns false.

Let’s visually run this algorithm:

Created with Fabric.js 3.6.6Initial state5712843val = 10hashsetvalue
1 of 6
C++
Java
Python
JS
Ruby
Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
bool FindSumOfTwo(vector<int>& nums, int val) {
    // Initializing a hash set
    unordered_set<int> found_values;
    // Traversing the nums list for each element 'ele'
    for (int& ele : nums) {
        // If (val - ele) is present in the hash set, there is
        // at least one value among those already traversed that,
        // added to ele, equals the target value
        if (found_values.find(val - ele) != found_values.end()) {
            return true;
        }
        // In case the current element does not pair up with one of those
        // already scanned, we add it to the hash set
        found_values.insert(ele);
    }
    // Return False if no sum is found
    return false;
}
int main() {
    vector<int> nums = {5, 7, 1, 2, 8, 4, 3};
    vector<int> test = {3, 20, 1, 2, 7};
    for (int i = 0; i < test.size(); i++) {
#
#include <iostream> #include <vector> #include <unordered_set> using namespace std; bool FindSumOfTwo(vector<int>& nums, int val) { // Initializing a hash set unordered_set<int> found_values;
Enter to Rename, Shift+Enter to Preview
Run
Save
Reset

Time complexity#

The time complexity of this solution is O(n)O(n)O(n).

Space complexity#

The space complexity of this solution is O(n)O(n)O(n).

Solution 2#

Note: This solution works only for the sorted array.

To understand the algorithm for this solution, let’s look at the pseudo-code below:

// assume 0 is the first index in array
// and n is the total number of elements in array
left = 0
right = n - 1
while left is less than right
    sum = array[left] + array[right]
    if sum == val return true
    if sum is less than val
        // sum is smaller than value
        // means pair can only exist to the
        // right of left element, so left element
        // should be moved one step next
        left = left + 1
    else
        // sum is greater than value
        // means pair can only exist to the
        // left of right element, so right element
        // should be moved one step previous
        right = right - 1

Let’s see a visual representation of the algorithm:

Created with Fabric.js 3.6.6Initial state134571415val = 11
1 of 7
C++
Java
Python
JS
Ruby
Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool FindSumOfTwo(vector<int>& nums, int val) {
    // Sort the array
    sort(nums.begin(), nums.end());
    // Initializing markers i and j
    int i = 0;
    int j = nums.size() - 1;
    while (< j) {
        // Adding two marker's elements
        int sum = nums[i] + nums[j];
        // Return true if nums_sum is equal to the val
        if (sum == val) {
            return true;
        }
        // Updating low-end marker 'i' if nums_sum is less than the target value
        if (sum < val) {
            ++i;
        }
        // Updating high-end marker 'j' if nums_sum is greater than the target value
        else {
#
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool FindSumOfTwo(vector<int>& nums, int val) { // Sort the array sort(nums.begin(), nums.end());
Enter to Rename, Shift+Enter to Preview
Run
Save
Reset

Time complexity#

The time complexity of this solution is O(n logn)O(n\,logn)O(nlogn).

Space complexity#

The space complexity of this solution is O(1)O(1)O(1).

Back
Merge an Array With Overlapping Intervals
Next
Sort an Array Using Quicksort Algorithm
Mark as Completed
Report an Issue


Creation date: Oct 7, 2022 7:33pm     Last modified date: Oct 7, 2022 7:33pm   Last visit date: Dec 6, 2024 7:50am
    Report Objectionable Content