Open In App

Two Sum – Pair with given Sum

Last Updated : 21 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an array arr[] of n integers and a target value, the task is to find whether there is a pair of elements in the array whose sum is equal to target. This problem is a variation of 2Sum problem.

Examples: 

Input: arr[] = [0, -1, 2, -3, 1], target = -2
Output: true
Explanation: There is a pair (1, -3) with the sum equal to given target, 1 + (-3) = -2.

Input: arr[] = [1, -2, 1, 0, 5], target = 0
Output: false
Explanation: There is no pair with sum equals to given target.

[Naive Approach] Generating all Possible Pairs – O(n^2) time and O(1) space

The very basic approach is to generate all the possible pairs and check if any of them add up to the target value. To generate all pairs, we simply run two nested loops.

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to check whether any pair exists
// whose sum is equal to the given target value
bool twoSum(vector<int> &arr, int target) {
    int n = arr.size();

    // Iterate through each element in the array
    for (int i = 0; i < n; i++) {
      
        // For each element arr[i], check every
        // other element arr[j] that comes after it
        for (int j = i + 1; j < n; j++) {
          
            // Check if the sum of the current pair
            // equals the target
            if (arr[i] + arr[j] == target) {
                return true;
            }
        }
    }
  
    // If no pair is found after checking
    // all possibilities
    return false;
}

int main() {
  
    vector<int> arr = {0, -1, 2, -3, 1};
    int target = -2;

    // Call the twoSum function and print the result
    if(twoSum(arr, target))
      cout << "true";
    else
      cout << "false";

    return 0;
}
C Java Python C# JavaScript

Output
true

Time Complexity: O(n²), for using two nested loops
Auxiliary Space: O(1)

[Better Approach 1] Sorting and Binary Search – O(n*log(n)) time and O(1) space

We can also solve this problem using Binary Search. As we know that searching element in sorted array would take O(log(n)) time. We first sort the array. Then for each number arr[i] in the array, we first calculate its complement (i.e., target – current number) then uses binary search to quickly check if this complement exists in the subarray after index i. If we find the complement, we returns true; If we never find a complement (after checking all numbers), we return false.

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Function to perform binary search
bool binarySearch(vector<int> &arr, int left, int right, int target){
    while (left <= right){
        int mid = left + (right - left) / 2;

        if (arr[mid] == target)
            return true;
        if (arr[mid] < target)
            left = mid + 1;
        else
            right = mid - 1;
    }
    return false;
}

// Function to check whether any pair exists
// whose sum is equal to the given target value
bool twoSum(vector<int> &arr, int target){
    
    sort(arr.begin(), arr.end());

    // Iterate through each element in the array
    for (int i = 0; i < arr.size(); i++){
        int complement = target - arr[i];

        // Use binary search to find the complement
        if (binarySearch(arr, i + 1, arr.size() - 1, complement))
            return true;
    }
  
    // If no pair is found
    return false;
}

int main(){
    vector<int> arr = {0, -1, 2, -3, 1};
    int target = -2;

    if (twoSum(arr, target))
        cout << "true";
    else
        cout << "false";

    return 0;
}
C Java Python C# JavaScript

Output
true

Time Complexity: O(n*log(n)), for sorting the array
Auxiliary Space: O(1)

[Better Approach 2] Sorting and Two-Pointer Technique – O(n*log(n)) time and O(1) space

The idea is to use the two-pointer technique but for using the two-pointer technique, the array must be sorted. Once the array is sorted then we can use this approach by keeping one pointer at the beginning (left) and another at the end (right) of the array. Then check the sum of the elements at these two pointers:

  • If the sum equals the target, we’ve found the pair.
  • If the sum is less than the target, move the left pointer to the right to increase the sum.
  • If the sum is greater than the target, move the right pointer to the left to decrease the sum.

Illustration:


C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Function to check whether any pair exists
// whose sum is equal to the given target value
bool twoSum(vector<int> &arr, int target){
  
    // Sort the array
    sort(arr.begin(), arr.end());

    int left = 0, right = arr.size() - 1;

    // Iterate while left pointer is less than right
    while (left < right){
        int sum = arr[left] + arr[right];

        // Check if the sum matches the target
        if (sum == target)
            return true;
        else if (sum < target)
            left++; // Move left pointer to the right
        else
            right--; // Move right pointer to the left
    }
    // If no pair is found
    return false;
}

int main(){
    vector<int> arr = {0, -1, 2, -3, 1};
    int target = -2;

    // Call the twoSum function and print the result
    if (twoSum(arr, target))
        cout << "true";
    else
        cout << "false";

    return 0;
}
C Java Python C# JavaScript

Output
true

Time Complexity: O(n*log(n)), for sorting the array
Auxiliary Space: O(1)

Note : This approach is the best approach for a sorted array. But if array is not sorted, then we use the below approach.

[Expected Approach] Using Hash Set – O(n) time and O(n) space

Hashing provides a more efficient solution to the 2Sum problem. Rather than checking every possible pair, we store each number in an unordered set during iterating over the array’s elements. For each number, we calculate its complement (i.e., target – current number) and check if this complement exists in the set. If it does, we have successfully found the pair that sums to the target. This approach significantly reduces the time complexity and allowing us to solve the problem in linear time O(n).

Step-by-step approach:

  • Create an empty Hash Set or Unordered Set
  • Iterate through the array and for each number in the array:
    • Calculate the complement (target – current number).
    • Check if the complement exists in the set:
      • If it is, then pair found.
      • If it isn’t, add the current number to the set.
  • If the loop completes without finding a pair, return that no pair exists.
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

// Function to check whether any pair exists
// whose sum is equal to the given target value
bool twoSum(vector<int> &arr, int target){
  
    // Create an unordered_set to store the elements
    unordered_set<int> s;

    // Iterate through each element in the vector
    for (int i = 0; i < arr.size(); i++){

        // Calculate the complement that added to
        // arr[i], equals the target
        int complement = target - arr[i];

        // Check if the complement exists in the set
        if (s.find(complement) != s.end())
            return true;

        // Add the current element to the set
        s.insert(arr[i]);
    }
  
    // If no pair is found
    return false;
}

int main(){
    vector<int> arr = {0, -1, 2, -3, 1};
    int target = -2;

    if (twoSum(arr, target))
        cout << "true";
    else
        cout << "false";

    return 0;
}
Java Python C# JavaScript

Output
true

Time Complexity: O(n), for single iteration over the array
Auxiliary Space: O(n), for hash set.

Related Problems:  



Next Article

Similar Reads

three90RightbarBannerImg