Given an array arr[] of n integers and a target value, check if there exists a pair whose sum equals the target. This is a variation of the 2-Sum 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
The 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.
#include<iostream>
#include<vector>
usingnamespacestd;
booltwoSum(vector<int>&arr,inttarget){
intn=arr.size();
for(inti=0;i<n;i++){
// For each element arr[i], check every
// other element arr[j] that comes after it
for(intj=i+1;j<n;j++){
// Check if the sum of the current pair
// equals the target
if(arr[i]+arr[j]==target){
returntrue;
}
}
}
// If no pair is found after checking
// all possibilities
returnfalse;
}
intmain(){
vector<int>arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
cout<<"true";
else
cout<<"false";
return0;
}
#include<stdbool.h>
#include<stdio.h>
booltwoSum(intarr[],intn,inttarget){
for(inti=0;i<n;i++){
// For each element arr[i], check every
// other element arr[j] that comes after it
for(intj=i+1;j<n;j++){
// Check if the sum of the current pair
// equals the target
if(arr[i]+arr[j]==target)
returntrue;
}
}
// If no pair is found after checking
// all possibilities
returnfalse;
}
intmain(){
intarr[]={0,-1,2,-3,1};
inttarget=-2;
intn=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");
return0;
}
class GfG{
staticbooleantwoSum(int[]arr,inttarget){
intn=arr.length;
for(inti=0;i<n;i++){
// For each element arr[i], check every
// other element arr[j] that comes after it
for(intj=i+1;j<n;j++){
// Check if the sum of the current pair
// equals the target
if(arr[i]+arr[j]==target){
returntrue;
}
}
}
// If no pair is found after checking
// all possibilities
returnfalse;
}
publicstaticvoidmain(String[]args){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
System.out.println("true");
else
System.out.println("false");
}
}
def twoSum(arr, target):
n = len(arr)
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")
usingSystem;
classGfG{
staticbooltwoSum(int[]arr,inttarget){
intn=arr.Length;
for(inti=0;i<n;i++){
// For each element arr[i], check every
// other element arr[j] that comes after it
for(intj=i+1;j<n;j++){
// Check if the sum of the current pair
// equals the target
if(arr[i]+arr[j]==target){
returntrue;
}
}
}
// If no pair is found after checking
// all possibilities
returnfalse;
}
staticvoidMain(){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
functiontwoSum(arr,target){
letn=arr.length;
for(leti=0;i<n;i++){
// For each element arr[i], check every
// other element arr[j] that comes after it
for(letj=i+1;j<n;j++){
// Check if the sum of the current pair
// equals the target
if(arr[i]+arr[j]===target){
returntrue;
}
}
}
// If no pair is found after checking
// all possibilities
returnfalse;
}
// Driver Code
letarr=[0,-1,2,-3,1];
lettarget=-2;
if(twoSum(arr,target))
console.log("true");
else
console.log("false");
true
To check if a pair with a given sum exists in the array, we first sort the array. Then for each element, we compute the required complement (i.e., target - arr[i]) and perform binary search on the remaining subarray (from index i+1 to end) to find that complement.
Step By Step Implementation:
#include<iostream>
#include<vector>
#include<algorithm>
usingnamespacestd;
// Function to perform binary search
boolbinarySearch(vector<int>&arr,intleft,
intright,inttarget){
while(left<=right){
intmid=left+(right-left)/2;
if(arr[mid]==target)
returntrue;
if(arr[mid]<target)
left=mid+1;
else
right=mid-1;
}
returnfalse;
}
booltwoSum(vector<int>&arr,inttarget){
sort(arr.begin(),arr.end());
for(inti=0;i<arr.size();i++){
intcomplement=target-arr[i];
// Use binary search to
// find the complement
if(binarySearch(arr,i+1,
arr.size()-1,complement))
returntrue;
}
// If no pair is found
returnfalse;
}
intmain(){
vector<int>arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
cout<<"true";
else
cout<<"false";
return0;
}
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
// Comparison function for qsort
intcompare(constvoid*a,constvoid*b){
return(*(int*)a-*(int*)b);
}
// Function to perform binary search
boolbinarySearch(intarr[],intleft,
intright,inttarget){
while(left<=right){
intmid=left+(right-left)/2;
if(arr[mid]==target)
returntrue;
if(arr[mid]<target)
left=mid+1;
else
right=mid-1;
}
returnfalse;
}
booltwoSum(intarr[],intn,inttarget){
qsort(arr,n,sizeof(int),compare);
for(inti=0;i<n;i++){
intcomplement=target-arr[i];
// Use binary search to
// find the complement
if(binarySearch(arr,i+1,
n-1,complement))
returntrue;
}
// If no pair is found
returnfalse;
}
intmain(){
intarr[]={0,-1,2,-3,1};
inttarget=-2;
intn=sizeof(arr)/sizeof(arr[0]);
if(twoSum(arr,n,target))
printf("true\n");
else
printf("false\n");
return0;
}
importjava.util.Arrays;
class GfG{
// Function to perform binary search
staticbooleanbinarySearch(int[]arr,intleft,
intright,inttarget){
while(left<=right){
intmid=left+(right-left)/2;
if(arr[mid]==target)
returntrue;
if(arr[mid]<target)
left=mid+1;
else
right=mid-1;
}
returnfalse;
}
staticbooleantwoSum(int[]arr,inttarget){
Arrays.sort(arr);
for(inti=0;i<arr.length;i++){
intcomplement=target-arr[i];
// Use binary search to find the complement
if(binarySearch(arr,i+1,arr.length-1,
complement))
returntrue;
}
// If no pair is found
returnfalse;
}
publicstaticvoidmain(String[]args){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target)){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
# Function to perform binary search
def binarySearch(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
def twoSum(arr, target):
arr.sort()
for i in range(len(arr)):
complement = target - arr[i]
# Use binary search to find the complement
if binarySearch(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")
usingSystem;
classGfG{
// Function to perform binary search
staticboolbinarySearch(int[]arr,intleft,
intright,inttarget){
while(left<=right){
intmid=left+(right-left)/2;
if(arr[mid]==target)
returntrue;
if(arr[mid]<target)
left=mid+1;
else
right=mid-1;
}
returnfalse;
}
staticbooltwoSum(int[]arr,inttarget){
Array.Sort(arr);
for(inti=0;i<arr.Length;i++){
intcomplement=target-arr[i];
// Use binary search to find the complement
if(binarySearch(arr,i+1,arr.Length-1,
complement))
returntrue;
}
// If no pair is found
returnfalse;
}
staticvoidMain(){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target)){
Console.WriteLine("true");
}
else{
Console.WriteLine("false");
}
}
}
// Function to perform binary search
functionbinarySearch(arr,left,right,target){
while(left<=right){
letmid=Math.floor(left+(right-left)/2);
if(arr[mid]===target)
returntrue;
if(arr[mid]<target)
left=mid+1;
else
right=mid-1;
}
returnfalse;
}
functiontwoSum(arr,target){
arr.sort((a,b)=>a-b);
for(leti=0;i<arr.length;i++){
letcomplement=target-arr[i];
// Use binary search to find the complement
if(binarySearch(arr,i+1,
arr.length-1,complement))
returntrue;
}
// If no pair is found
returnfalse;
}
// Driver Code
letarr=[0,-1,2,-3,1];
lettarget=-2;
if(twoSum(arr,target)){
console.log("true");
}else{
console.log("false");
}
true
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.
Check the sum of the elements at these two pointers:
Note: This approach is the best approach for a sorted array. But if array is not sorted, then we use the below approach.
#include<iostream>
#include<vector>
#include<algorithm>
usingnamespacestd;
booltwoSum(vector<int>&arr,inttarget){
sort(arr.begin(),arr.end());
intleft=0,right=arr.size()-1;
// Iterate while left pointer
// is less than right
while(left<right){
intsum=arr[left]+arr[right];
// Check if the sum matches the target
if(sum==target)
returntrue;
elseif(sum<target)
// Move left pointer to the right
left++;
else
// Move right pointer to the left
right--;
}
// If no pair is found
returnfalse;
}
intmain(){
vector<int>arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
cout<<"true";
else
cout<<"false";
return0;
}
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
// Comparison function for qsort
intcompare(constvoid*a,constvoid*b){
return(*(int*)a-*(int*)b);
}
booltwoSum(intarr[],intn,inttarget){
qsort(arr,n,sizeof(int),compare);
intleft=0,right=n-1;
// Iterate while left pointer is less than right
while(left<right){
intsum=arr[left]+arr[right];
// Check if the sum matches the target
if(sum==target)
returntrue;
elseif(sum<target)
// Move left pointer to the right
left++;
else
// Move right pointer to the left
right--;
}
// If no pair is found
returnfalse;
}
intmain(){
intarr[]={0,-1,2,-3,1};
inttarget=-2;
intn=sizeof(arr)/sizeof(arr[0]);
if(twoSum(arr,n,target))
printf("true\n");
else
printf("false\n");
return0;
}
importjava.util.Arrays;
class GfG{
staticbooleantwoSum(int[]arr,inttarget){
Arrays.sort(arr);
intleft=0,right=arr.length-1;
// Iterate while left pointer is less than right
while(left<right){
intsum=arr[left]+arr[right];
// Check if the sum matches the target
if(sum==target)
returntrue;
elseif(sum<target)
// Move left pointer to the right
left++;
else
// Move right pointer to the left
right--;
}
// If no pair is found
returnfalse;
}
publicstaticvoidmain(String[]args){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target)){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
def twoSum(arr, target):
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:
# Move left pointer to the right
left += 1
else:
# Move right pointer to the left
right -= 1
# 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")
usingSystem;
usingSystem.Linq;
classGfG{
staticbooltwoSum(int[]arr,inttarget){
Array.Sort(arr);
intleft=0,right=arr.Length-1;
// Iterate while left pointer is less than right
while(left<right){
intsum=arr[left]+arr[right];
// Check if the sum matches the target
if(sum==target)
returntrue;
elseif(sum<target)
// Move left pointer to the right
left++;
else
// Move right pointer to the left
right--;
}
// If no pair is found
returnfalse;
}
staticvoidMain(){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
functiontwoSum(arr,target)
{
arr.sort((a,b)=>a-b);
letleft=0,right=arr.length-1;
// Iterate while left pointer is less than right
while(left<right){
letsum=arr[left]+arr[right];
// Check if the sum matches the target
if(sum===target)
returntrue;
elseif(sum<target)
// Move left pointer to the right
left++;
else
// Move right pointer to the left
right--;
}
// If no pair is found
returnfalse;
}
// Driver Code
letarr=[0,-1,2,-3,1];
lettarget=-2;
if(twoSum(arr,target)){
console.log("true");
}else{
console.log("false");
}
true
Hashing provides a more efficient solution to the 2-Sum 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.
Step By Step Implementations:
#include<iostream>
#include<vector>
#include<unordered_set>
usingnamespacestd;
booltwoSum(vector<int>&arr,inttarget){
// Create an unordered_set to store the elements
unordered_set<int>s;
for(inti=0;i<arr.size();i++){
// Calculate the complement that added to
// arr[i], equals the target
intcomplement=target-arr[i];
// Check if the complement exists in the set
if(s.find(complement)!=s.end())
returntrue;
// Add the current element to the set
s.insert(arr[i]);
}
// If no pair is found
returnfalse;
}
intmain(){
vector<int>arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
cout<<"true";
else
cout<<"false";
return0;
}
importjava.util.HashSet;
class GfG{
staticbooleantwoSum(int[]arr,inttarget){
// Create a HashSet to store the elements
HashSet<Integer>set=newHashSet<>();
for(inti=0;i<arr.length;i++){
// Calculate the complement that added to
// arr[i], equals the target
intcomplement=target-arr[i];
// Check if the complement exists in the set
if(set.contains(complement)){
returntrue;
}
// Add the current element to the set
set.add(arr[i]);
}
// If no pair is found
returnfalse;
}
publicstaticvoidmain(String[]args){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
System.out.println("true");
else
System.out.println("false");
}
}
def twoSum(arr, target):
# Create a set to store the elements
s = set()
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
if __name__ == "__main__":
arr = [0, -1, 2, -3, 1]
target = -2
if twoSum(arr, target):
print("true")
else:
print("false")
usingSystem;
usingSystem.Collections.Generic;
classGfG{
staticbooltwoSum(int[]arr,inttarget){
// Create a HashSet to store the elements
HashSet<int>set=newHashSet<int>();
for(inti=0;i<arr.Length;i++){
// Calculate the complement that added to
// arr[i], equals the target
intcomplement=target-arr[i];
// Check if the complement exists in the set
if(set.Contains(complement))
returntrue;
// Add the current element to the set
set.Add(arr[i]);
}
// If no pair is found
returnfalse;
}
staticvoidMain(){
int[]arr={0,-1,2,-3,1};
inttarget=-2;
if(twoSum(arr,target))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
functiontwoSum(arr,target){
// Create a Set to store the elements
letset=newSet();
for(letnumofarr){
// Calculate the complement that added to
// num, equals the target
letcomplement=target-num;
// Check if the complement exists in the set
if(set.has(complement)){
returntrue;
}
// Add the current element to the set
set.add(num);
}
// If no pair is found
returnfalse;
}
// Driver Code
letarr=[0,-1,2,-3,1];
lettarget=-2;
if(twoSum(arr,target))
console.log("true");
else
console.log("false");
true
Array Data Structure
String in Data Structure
Hashing in Data Structure
Linked List Data Structure
Stack Data Structure
Queue Data Structure
Tree Data Structure
Graph Data Structure
Trie Data Structure
Searching Algorithms
Sorting Algorithms
Introduction to Recursion
Greedy Algorithms
Graph Algorithms
Dynamic Programming or DP
Bitwise Algorithms
Segment Tree
Binary Indexed Tree or Fenwick Tree
Square Root (Sqrt) Decomposition Algorithm
Binary Lifting
Geometry