2 Sum - Find a pair with given sum
Last Updated :
01 Oct, 2024
Given an array of integers arr[] and an integer target, print a pair of two numbers such that they add up to target. You cannot use the same element twice.
Examples:
Input: arr[] = {2, 9, 10, 4, 15}, target = 12
Output: {2, 10}
Explanation: As sum of 2 and 10 is equal to 12.
Input: arr[] = {3, 2, 4}, target = 8
Output: { }
Explanation: As no such pair exist whose sum is equal to 8, so return empty array
[Naive Approach] Using Nested Loops - O(n^2) Time and O(1) Space
The idea is to check every possible pair of elements in the array to see if their sum equals the target value. This can be implemented using nested for loops, outer loop for first element and inner loop for second element of the pair. If sum of current two elements is equal to target then return this pair.
C++
// C++ program to find two numbers of array
// such that they add up to target.
#include <iostream>
#include <vector>
using namespace std;
// function to find two sum pair
vector<int> twoSum(vector<int>& arr, int target) {
vector<int> res;
// Check all possible pairs
for(int i = 0; i < arr.size(); i++) {
for(int j = i+1; j < arr.size(); j++) {
// If sum of current pair is equal
// to target then copy it to result
if(arr[i] + arr[j] == target) {
res.push_back(arr[i]);
res.push_back(arr[j]);
return res;
}
}
}
return res;
}
int main() {
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find two numbers of array
// such that they add up to target.
#include <stdio.h>
// Function to find two sum pair
int* twoSum(int arr[], int n, int target, int* resSize) {
int* res = (int*)malloc(2 * sizeof(int));
// Check all possible pairs
for(int i = 0; i < n - 1; i++) {
for(int j = i + 1; j < n; j++) {
// If sum of current pair is equal
// to target then copy it to result
if(arr[i] + arr[j] == target) {
res[0] = arr[i];
res[1] = arr[j];
*resSize = 2;
return res;
}
}
}
return res;
}
int main() {
int arr[] = {2, 9, 10, 4, 15};
int n = sizeof(arr)/sizeof(arr[0]);
int target = 12;
int resSize = 0;
int* res = twoSum(arr, n, target, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find two numbers of array
// such that they add up to target.
import java.util.List;
import java.util.ArrayList;
class GfG {
// function to find two sum pair
static int[] twoSum(int[] arr, int target) {
int[] res = {};
// Check all possible pairs
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
// If sum of current pair is equal
// to target then copy it to result
if (arr[i] + arr[j] == target) {
res = new int[2];
res[0] = arr[i];
res[1] = arr[j];
return res;
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
int[] res = twoSum(arr, target);
for (int x : res) {
System.out.print(x + " ");
}
}
}
Python
# Python program to find two numbers of array
# such that they add up to target
def twoSum(arr, target):
res = []
# Check all possible pairs
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
# If sum of current pair is equal
# to target then copy it to result
if arr[i] + arr[j] == target:
res = [arr[i], arr[j]]
return res
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for x in res:
print(x, end=" ")
C#
// C# program to find two numbers of array
// such that they add up to target.
using System;
class GfG {
static int[] twoSum(int[] arr, int target) {
int[] res = { };
// Check all possible pairs
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
// If sum of current pair is equal
// to target then copy it to result
if (arr[i] + arr[j] == target) {
res = new int[] {arr[i], arr[j]};
return res;
}
}
}
return res;
}
static void Main() {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
int[] res = twoSum(arr, target);
foreach (int x in res) {
Console.Write(x + " ");
}
}
}
JavaScript
// JavaScript program to find two numbers of array
// such that they add up to target.
function twoSum(arr, target) {
let res = [ ];
// Check all possible pairs
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
// If sum of current pair is equal
// to target then copy it to result
if (arr[i] + arr[j] === target) {
res = [arr[i], arr[j]];
return res;
}
}
}
return res;
}
let arr = [2, 9, 10, 4, 15];
let target = 12;
let res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n^2), as we are generating all the pairs 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. The idea is to sort the array and for each number, we calculate its complement ( target - current number ) and then use binary search to check if the complement exists in the remaining elements of the array. If a valid pair is found, we return it. Otherwise, we return empty array.
C++
// C++ program to find pair with given sum
// using sorting and binary search
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to perform binary search
int binarySearch(vector<int> &arr, int lo, int hi, int target) {
while (lo <= hi){
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
vector<int> twoSum(vector<int> &arr, int target) {
int n = arr.size();
vector<int> res = { };
sort(arr.begin(), arr.end());
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res.push_back(arr[i]);
res.push_back(arr[idx]);
break;
}
}
return res;
}
int main() {
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find pair with given sum
// using sorting and binary search
#include <stdio.h>
// Function to perform binary search
int binarySearch(int arr[], int lo, int hi, int target) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// 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
int* twoSum(int arr[], int n, int target, int* resSize) {
int* res = (int*)malloc(2 * sizeof(int));
*resSize = 0;
// Sorting the array using qsort
qsort(arr, n, sizeof(int), compare);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res[0] = arr[i];
res[1] = arr[idx];
*resSize = 2;
break;
}
}
return res;
}
int main() {
int arr[] = {2, 9, 10, 4, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 12;
int resSize;
int* res = twoSum(arr, n, target, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find pair with given sum
// using sorting and binary search
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to perform binary search
static int binarySearch(int[] arr, int lo, int hi, int target) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<Integer> twoSum(int[] arr, int target) {
int n = arr.length;
List<Integer> res = new ArrayList<>();
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res.add(arr[i]);
res.add(arr[idx]);
break;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
List<Integer> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python program to find pair with given sum
# using sorting and binary search
# Function to perform binary search
def binarySearch(arr, lo, hi, target):
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
# Function to check whether any pair exists
# whose sum is equal to the given target value
def twoSum(arr, target):
n = len(arr)
res = []
arr.sort()
for i in range(n):
complement = target - arr[i]
# Use binary search to find the complement
idx = binarySearch(arr, i + 1, n - 1, complement)
if idx != -1:
res.append(arr[i])
res.append(arr[idx])
break
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for x in res:
print(x, end=" ")
C#
// C# program to find pair with given sum
// using sorting and binary search
using System;
using System.Collections.Generic;
class GfG {
// Function to perform binary search
static int binarySearch(int[] arr, int lo, int hi, int target) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<int> twoSum(int[] arr, int target) {
int n = arr.Length;
List<int> res = new List<int>();
Array.Sort(arr);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Use binary search to find the complement
int idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx != -1) {
res.Add(arr[i]);
res.Add(arr[idx]);
break;
}
}
return res;
}
static void Main() {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
List<int> res = twoSum(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find pair with given sum
// using sorting and binary search
// Function to perform binary search
function binarySearch(arr, lo, hi, target) {
while (lo <= hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (arr[mid] === target)
return mid;
if (arr[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
return -1;
}
// Function to check whether any pair exists
// whose sum is equal to the given target value
function twoSum(arr, target) {
const n = arr.length;
const res = [];
arr.sort((a, b) => a - b);
for (let i = 0; i < n; i++) {
const complement = target - arr[i];
// Use binary search to find the complement
const idx = binarySearch(arr, i + 1, n - 1, complement);
if (idx !== -1) {
res.push(arr[i]);
res.push(arr[idx]);
break;
}
}
return res;
}
const arr = [2, 9, 10, 4, 15];
const target = 12;
const res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n*log(n)), for sorting the array.
Auxiliary Space: O(1)
[Better Approach 2] Sorting and Two Pointers – O(n*log(n)) Time and O(1) Space
The approach involves using the two pointer technique, which requires the array to be sorted first. After sorting, we can set one pointer at the beginning (left) and another at the end (right) of the array. We then check the sum of the elements at these two pointers:
- If sum < target, move left pointer to the right to increase the sum.
- If sum > target, move right pointer to the left to decrease the sum.
- If sum == target, we've found the pair.
C++
// C++ program to find pair with given sum
// using sorting and two pointers
#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
vector<int> twoSum(vector<int> &arr, int target){
vector<int> res = {};
// 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) {
res = {arr[left], arr[right]};
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
int main(){
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
C
// C program to find pair with given sum
// using sorting and two pointers
#include <stdio.h>
// Function to compare two integers 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
int* twoSum(int *arr, int size, int target, int *resSize) {
*resSize = 0;
qsort(arr, size, sizeof(int), compare);
int left = 0, right = size - 1;
while (left < right) {
int sum = arr[left] + arr[right];
// Check if the sum matches the target
if (sum == target) {
static int res[2];
res[0] = arr[left];
res[1] = arr[right];
*resSize = 2;
return res;
}
else if (sum < target)
left++;
else
right--;
}
// No pair found
return NULL;
}
int main() {
int arr[] = {2, 9, 10, 4, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 12;
int resSize;
int *res = twoSum(arr, n, target, &resSize);
for (int i = 0; i < resSize; i++)
printf("%d ", res[i]);
return 0;
}
Java
// Java program to find pair with given sum
// using sorting and two pointers
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to check whether any pair exists
// whose sum is equal to the given target value
static List<Integer> twoSum(int[] arr, int target) {
List<Integer> res = new ArrayList<>();
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) {
res.add(arr[left]);
res.add(arr[right]);
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
List<Integer> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
System.out.print(res.get(i) + " ");
}
}
Python
# Python program to find pair with given sum
# using sorting and two pointers
# Function to check whether any pair exists
# whose sum is equal to the given target value
def twoSum(arr, target):
res = []
arr.sort()
left = 0
right = 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:
res = [arr[left], arr[right]]
break
elif sum < target:
left += 1
else:
right -= 1
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for x in res:
print(x, end=" ")
C#
// C# program to find pair with given sum
// using sorting and two pointers
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 List<int> twoSum(List<int> arr, int target) {
List<int> res = new List<int>();
arr.Sort();
int left = 0, right = arr.Count - 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) {
res.Add(arr[left]);
res.Add(arr[right]);
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> {2, 9, 10, 4, 15};
int target = 12;
List<int> res = twoSum(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find pair with given sum
// using sorting and two pointers
// Function to check whether any pair exists
// whose sum is equal to the given target value
function twoSum(arr, target) {
let res = [];
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) {
res = [arr[left], arr[right]];
break;
}
else if (sum < target)
left++;
else
right--;
}
return res;
}
const arr = [2, 9, 10, 4, 15];
const target = 12;
const res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n*log(n)), for sorting the array
Auxiliary Space: O(1)
[Expected Approach] Using Hash Set – O(n) Time and O(n) Space
The idea is to store each number in hash set while iterating over the elements. For each element, we calculate its complement (i.e., target – current number) and check if this complement exists in the set. If it does, we have found the pair with sum equal to target.
C++
// C++ program to find pair with given sum
// using HashSet
#include <bits/stdc++.h>
using namespace std;
// Function to find a pair whose sum is equal to
// the given target value
vector<int> twoSum(vector<int> &arr, int target){
vector<int> res = { };
unordered_set<int> st;
for (int i = 0; i < arr.size(); i++){
// Calculate the complement such that
// arr[i] + complement = target
int complement = target - arr[i];
// Check if the complement exists in the set
if (st.find(complement) != st.end()){
res.push_back(complement);
res.push_back(arr[i]);
break;
}
// Add the current element to the set
st.insert(arr[i]);
}
return res;
}
int main(){
vector<int> arr = {2, 9, 10, 4, 15};
int target = 12;
vector<int> res = twoSum(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
return 0;
}
Java
// Java program to find pair with given sum
// using HashSet
import java.util.HashSet;
class GfG {
// Function to find a pair whose sum is equal to
// the given target value
static int[] twoSum(int[] arr, int target) {
int[] res = new int[2];
HashSet<Integer> st = new HashSet<>();
for (int i = 0; i < arr.length; i++) {
// Calculate the complement such that
// arr[i] + complement = target
int complement = target - arr[i];
// Check if the complement exists in the set
if (st.contains(complement)) {
res[0] = complement;
res[1] = arr[i];
return res;
}
// Add the current element to the set
st.add(arr[i]);
}
return new int[0];
}
public static void main(String[] args) {
int[] arr = {2, 9, 10, 4, 15};
int target = 12;
int[] res = twoSum(arr, target);
for (int i = 0; i < res.length; i++) {
if (res.length > 0) {
System.out.print(res[i] + " ");
}
}
}
}
Python
# Python program to find pair with given sum
# using HashSet
# Function to find a pair whose sum is equal to
# the given target value
def twoSum(arr, target):
res = []
st = set()
for i in range(len(arr)):
# Calculate the complement such that
# arr[i] + complement = target
complement = target - arr[i]
# Check if the complement exists in the set
if complement in st:
res.append(complement)
res.append(arr[i])
break
# Add the current element to the set
st.add(arr[i])
return res
if __name__ == "__main__":
arr = [2, 9, 10, 4, 15]
target = 12
res = twoSum(arr, target)
for i in range(len(res)):
print(res[i], end=" ")
C#
// C# program to find pair with given sum
// using HashSet
using System;
using System.Collections.Generic;
class GfG {
// Function to find a pair whose sum is equal to
// the given target value
static List<int> twoSum(List<int> arr, int target) {
List<int> res = new List<int>();
HashSet<int> st = new HashSet<int>();
for (int i = 0; i < arr.Count; i++) {
// Calculate the complement such that
// arr[i] + complement = target
int complement = target - arr[i];
// Check if the complement exists in the set
if (st.Contains(complement)) {
res.Add(complement);
res.Add(arr[i]);
break;
}
// Add the current element to the set
st.Add(arr[i]);
}
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> {2, 9, 10, 4, 15};
int target = 12;
List<int> res = twoSum(arr, target);
for (int i = 0; i < res.Count; i++)
Console.Write(res[i] + " ");
}
}
JavaScript
// JavaScript program to find pair with given sum
// using HashSet
// Function to find a pair whose sum is equal to
// the given target value
function twoSum(arr, target) {
let res = [];
let st = new Set();
for (let i = 0; i < arr.length; i++) {
// Calculate the complement such that
// arr[i] + complement = target
let complement = target - arr[i];
// Check if the complement exists in the set
if (st.has(complement)) {
res.push(complement);
res.push(arr[i]);
break;
}
// Add the current element to the set
st.add(arr[i]);
}
return res;
}
const arr = [2, 9, 10, 4, 15];
const target = 12;
const res = twoSum(arr, target);
console.log(res.join(" "));
Time Complexity: O(n), for single iteration over the array
Auxiliary Space: O(n) as we are using hash set to store the elements.
Similar Reads
2 Sum - Find All Pairs With Given Sum Given an array arr[] and a target value, the task is to find all possible indices (i, j) of pairs (arr[i], arr[j]) whose sum is equal to target and i != j. We can return pairs in any order, but all the returned pairs should be internally sorted, that is for any pair(i, j), i should be less than j.Ex
9 min read
2 Sum â All distinct pairs with given sum Given an array arr[] of size n and an integer target, the task is to find all distinct pairs in the array whose sum is equal to target. We can return pairs in any order, but all the returned pairs should be internally sorted, i.e., for any pair [q1, q2] the following should follow: q1 <= q2 .Exam
15+ min read
2 Sum - Find All Pairs With Zero Sum Given an array arr[], the task is to find all possible indices (i, j) of pairs (arr[i], arr[j]) whose sum is equal to 0 and i != j. We can return pairs in any order, but all the returned pairs should be internally sorted, that is for any pair(i, j), i should be less than j.Examples: Input: arr[] = {
8 min read
Two Sum - Pair with given Sum 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 = -2Output: trueExplanation: There is a pair (1, -3
15+ min read
2 Sum - Count Pairs with given Sum in Sorted Array Given a sorted array arr[] and an integer target, the task is to find the number of pairs in the array whose sum is equal to target.Examples: Input: arr[] = [-1, 1, 5, 5, 7], target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7). Input: arr[] = [1, 1, 1, 1], target = 2Outpu
9 min read