Two Sum Pair with given Sum (original) (raw)

Last Updated : 21 Dec, 2024

Try it on GfG Practice redirect icon

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.

Table of Content

**[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 #include using namespace std;

// Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(vector &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

#include <stdbool.h> #include <stdio.h>

// Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(int arr[], int n, int target){

// 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(){

int arr[] = {0, -1, 2, -3, 1};
int target = -2;
int n = sizeof(arr) / sizeof(arr[0]);

// Call the twoSum function and print the result
if (twoSum(arr, n, target))
    printf("true\n");
else
    printf("false\n");

return 0;

}

Java

class GfG {

// Function to check whether any pair exists
// whose sum is equal to the given target value
static boolean twoSum(int[] arr, int target){
    int n = arr.length;

    // 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;
}

public static void main(String[] args){

    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;
  
    if (twoSum(arr, target))
        System.out.println("true");
    else
        System.out.println("false");
}

}

Python

Function to check whether any pair exists

whose sum is equal to the given target value

def twoSum(arr, target): n = len(arr)

# Iterate through each element in the array
for i in range(n):
  
    # For each element arr[i], check every
    # other element arr[j] that comes after it
    for j in range(i + 1, n):
      
        # 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

if name == "main": arr = [0, -1, 2, -3, 1] target = -2

if twoSum(arr, target):
    print("true")
else:
    print("false")

C#

using System;

class GfG {

// Function to check whether any pair exists
// whose sum is equal to the given target value
static bool twoSum(int[] arr, int target) {
    int n = arr.Length;

    // 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;
}

static void Main() {
  
    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    if (twoSum(arr, target))
      Console.WriteLine("true");
    else 
      Console.WriteLine("false");
}

}

JavaScript

// Function to check whether any pair exists // whose sum is equal to the given target value function twoSum(arr, target) { let n = arr.length;

// Iterate through each element in the array
for (let i = 0; i < n; i++) {

    // For each element arr[i], check every
    // other element arr[j] that comes after it
    for (let 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;

}

// Driver Code let arr = [0, -1, 2, -3, 1]; let target = -2;

if (twoSum(arr, target)) console.log("true"); else console.log("false");

`

**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 #include #include using namespace std;

// Function to perform binary search bool binarySearch(vector &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 &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 arr = {0, -1, 2, -3, 1}; int target = -2;

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

return 0;

}

C

#include <stdbool.h> #include <stdio.h> #include <stdlib.h>

// Comparison function for qsort int compare(const void *a, const void b){ return ((int *)a - *(int *)b); }

// Function to perform binary search bool binarySearch(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(int arr[], int n, int target){ // Sort the array qsort(arr, n, sizeof(int), compare);

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

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

}

int main(){ int arr[] = {0, -1, 2, -3, 1}; int target = -2; int n = sizeof(arr) / sizeof(arr[0]);

if (twoSum(arr, n, target))
    printf("true\n");
else
    printf("false\n");

return 0;

}

Java

import java.util.Arrays;

class GfG {

// Function to perform binary search
static boolean binarySearch(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
static boolean twoSum(int[] arr, int target){
    
    // Sort the array
    Arrays.sort(arr);

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

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

public static void main(String[] args){
    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    if (twoSum(arr, target)) {
        System.out.println("true");
    }
    else {
        System.out.println("false");
    }
}

}

Python

Function to perform binary search

def binary_search(arr, left, right, target): while left <= right: mid = left + (right - left) // 2

    if arr[mid] == target:
        return True
    elif 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

def twoSum(arr, target): arr.sort()

# Iterate through each element in the array
for i in range(len(arr)):
    complement = target - arr[i]

    # Use binary search to find the complement
    if binary_search(arr, i + 1, len(arr) - 1, complement):
        return True
# If no pair is found
return False
  

if name == "main": arr = [0, -1, 2, -3, 1] target = -2

if twoSum(arr, target):
    print("true")
else:
    print("false")

C#

using System;

class GfG {

// Function to perform binary search
static bool binarySearch(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
static bool twoSum(int[] arr, int target){
    // Sort the array
    Array.Sort(arr);

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

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

static void Main(){
    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    if (twoSum(arr, target)) {
        Console.WriteLine("true");
    }
    else {
        Console.WriteLine("false");
    }
}

}

JavaScript

// Function to perform binary search function binarySearch(arr, left, right, target) { while (left <= right) { let mid = Math.floor(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 function twoSum(arr, target) { // Sort the array arr.sort((a, b) => a - b);

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

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

}

// Driver Code let arr = [0, -1, 2, -3, 1]; let target = -2;

if (twoSum(arr, target)) { console.log("true"); } else { console.log("false"); }

`

**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:

**Illustration:

C++ `

#include #include #include using namespace std;

// Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(vector &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 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

#include <stdbool.h> #include <stdio.h> #include <stdlib.h>

// Comparison function for qsort int compare(const void *a, const void b){ return ((int *)a - *(int *)b); }

// Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(int arr[], int n, int target){ // Sort the array qsort(arr, n, sizeof(int), compare);

int left = 0, right = n - 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(){ int arr[] = {0, -1, 2, -3, 1}; int target = -2; int n = sizeof(arr) / sizeof(arr[0]);

// Call the twoSum function and print the result
if (twoSum(arr, n, target))
    printf("true\n"); 
else
    printf("false\n");

return 0;

}

Java

import java.util.Arrays;

class GfG {

// Function to check whether any pair exists
// whose sum is equal to the given target value
static boolean twoSum(int[] arr, int target){
    // Sort the array
    Arrays.sort(arr);

    int left = 0, right = arr.length - 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;
}

public static void main(String[] args){
    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    // Call the twoSum function and print the result
    if (twoSum(arr, target)) {
        System.out.println("true");
    }
    else {
        System.out.println("false");
    }
}

}

Python

Function to check whether any pair exists

whose sum is equal to the given target value

def two_sum(arr, target): # Sort the array arr.sort()

left, right = 0, len(arr) - 1

# Iterate while left pointer is less than right
while left < right:
    sum = arr[left] + arr[right]

    # Check if the sum matches the target
    if sum == target:
        return True
    elif sum < target: 
        left += 1  # Move left pointer to the right
    else:
        right -= 1 # Move right pointer to the left

# If no pair is found
return False

arr = [0, -1, 2, -3, 1] target = -2

Call the two_sum function and print the result

if two_sum(arr, target): print("true") else: print("false")

C#

using System; using System.Linq;

class GfG {

// Function to check whether any pair exists
// whose sum is equal to the given target value
static bool TwoSum(int[] arr, int target){
  
    // Sort the array
    Array.Sort(arr);

    int left = 0, right = arr.Length - 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;
}

static void Main(){
    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    // Call the TwoSum function and print the result
    if (TwoSum(arr, target))
        Console.WriteLine("true");
    else 
        Console.WriteLine("false");
}

}

JavaScript

// Function to check whether any pair exists // whose sum is equal to the given target value function twoSum(arr, target) { // Sort the array arr.sort((a, b) => a - b);

let left = 0, right = arr.length - 1;

// Iterate while left pointer is less than right
while (left < right) {
    let 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;

}

let arr = [ 0, -1, 2, -3, 1 ]; let target = -2;

// Call the twoSum function and print the result if (twoSum(arr, target)) { console.log("true"); } else { console.log("false"); }

`

**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

**Hashingprovides 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:

#include #include #include using namespace std;

// Function to check whether any pair exists // whose sum is equal to the given target value bool twoSum(vector &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 arr = {0, -1, 2, -3, 1}; int target = -2;

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

return 0;

}

Java

import java.util.HashSet;

class GfG {

// Function to check whether any pair exists
// whose sum is equal to the given target value
static boolean twoSum(int[] arr, int target){

    // Create a HashSet to store the elements
    HashSet<Integer> set = new HashSet<>();

    // Iterate through each element in the array
    for (int i = 0; i < arr.length; 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 (set.contains(complement)) {
            return true;
        }

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

public static void main(String[] args){

    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    // Call the twoSum function and print the result
    if (twoSum(arr, target))
        System.out.println("true");
    else
        System.out.println("false");
}

}

Python

Function to check whether any pair exists

whose sum is equal to the given target value

def twoSum(arr, target):

# Create a set to store the elements
s = set()

# Iterate through each element in the array
for num in arr:
  
    # Calculate the complement that added to
    # num, equals the target
    complement = target - num

    # Check if the complement exists in the set
    if complement in s:
        return True

    # Add the current element to the set
    s.add(num)

# If no pair is found
return False

arr = [0, -1, 2, -3, 1] target = -2

Call the two_sum function and print the result

if twoSum(arr, target): print("true") else: print("false")

C#

using System; using System.Collections.Generic;

class GfG {

// Function to check whether any pair exists
// whose sum is equal to the given target value
static bool TwoSum(int[] arr, int target){

    // Create a HashSet to store the elements
    HashSet<int> set = new HashSet<int>();

    // Iterate through each element in the array
    for (int i = 0; i < arr.Length; 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 (set.Contains(complement))
            return true;

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

static void Main(){
    int[] arr = { 0, -1, 2, -3, 1 };
    int target = -2;

    // Call the TwoSum function and print the result
    if (TwoSum(arr, target))
        Console.WriteLine("true");
    else 
        Console.WriteLine("false"); 
}

}

JavaScript

// Function to check whether any pair exists // whose sum is equal to the given target value function twoSum(arr, target) {

// Create a Set to store the elements
let set = new Set();

// Iterate through each element in the array
for (let num of arr) {

    // Calculate the complement that added to
    // num, equals the target
    let complement = target - num;

    // Check if the complement exists in the set
    if (set.has(complement)) {
        return true;
    }

    // Add the current element to the set
    set.add(num);
}
// If no pair is found
return false;

}

let arr = [0, -1, 2, -3, 1]; let target = -2;

// Call the twoSum function and print the result if (twoSum(arr, target)) console.log("true"); else console.log("false");

`

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