Print all pairs with given sum
Given an array of integers, and a number ‘sum’, print all unique pairs in the array whose sum is equal to ‘sum’.
Examples :
Input : arr[] = {1, 5, 7, -1, 5}, sum = 6
Output : (1, 5), (7, -1)
Input : arr[] = {2, 5, 17, -1} sum = 7
Output : (2, 5)
Print all pairs with given sum using Naive Approach
A simple solution is to traverse each element and check if there’s another number in the array which can be added to it to give sum, using set to handle duplicate pairs.
Below is the implementation of above approach:
C++
// C++ implementation of simple method to
// find print pairs with given sum.
#include <bits/stdc++.h>
using namespace std;
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
int printPairs(int arr[], int n, int sum)
{
int count = 0; // Initialize result
set<pair<int,int>> dup;
// Consider all possible pairs and check
// their sums
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
{
if(dup.find({arr[i],arr[j]})==dup.end() && dup.find({arr[j],arr[i]})==dup.end())
{
cout << "(" << arr[i] << ", " << arr[j]
<< ")" << endl;
dup.insert({arr[i],arr[j]});
}
}
}
// Driver function to test the above function
int main()
{
int arr[] = { 1, 5, 7, -1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 6;
printPairs(arr, n, sum);
return 0;
}
Java
// Java implementation of
// simple method to find
// print pairs with given sum.
class GFG {
// Returns number of pairs
// in arr[0..n-1] with sum
// equal to 'sum'
static void printPairs(int arr[], int n, int sum)
{
// int count = 0;
// Consider all possible pairs
// and check their sums
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
System.out.println("(" + arr[i] + ", "
+ arr[j] + ")");
}
// Driver Code
public static void main(String[] arg)
{
int arr[] = { 1, 5, 7, -1, 5 };
int n = arr.length;
int sum = 6;
printPairs(arr, n, sum);
}
}
// This code is contributed
// by Smitha
C#
// C# implementation of simple
// method to find print pairs
// with given sum.
using System;
class GFG {
// Returns number of pairs
// in arr[0..n-1] with sum
// equal to 'sum'
static void printPairs(int[] arr, int n, int sum)
{
// int count = 0;
// Consider all possible pairs
// and check their sums
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
Console.Write("(" + arr[i] + ", "
+ arr[j] + ")"
+ "\n");
}
// Driver Code
public static void Main()
{
int[] arr = { 1, 5, 7, -1, 5 };
int n = arr.Length;
int sum = 6;
printPairs(arr, n, sum);
}
}
// This code is contributed
// by Smitha
Javascript
<script>
// JavaScript implementation of simple method to
// find print pairs with given sum.
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
function printPairs(arr, n, sum)
{
let count = 0; // Initialize result
// Consider all possible pairs and check
// their sums
for (let i = 0; i < n; i++)
for (let j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
document.write("(" + arr[i] + ", "
+ arr[j] + ")" + "<br>");
}
// Driver function to test the above function
let arr = [ 1, 5, 7, -1, 5 ];
let n = arr.length;
let sum = 6;
printPairs(arr, n, sum);
// This code is contributed by Surbhi Tyagi
</script>
PHP
<?php
// PHP implementation of simple
// method to find print pairs
// with given sum.
// Returns number of pairs in
// arr[0..n-1] with sum equal
// to 'sum'
function printPairs($arr, $n, $sum)
{
// Initialize result
$count = 0;
// Consider all possible
// pairs and check their sums
for ($i = 0; $i < $n; $i++)
for ( $j = $i + 1; $j < $n; $j++)
if ($arr[$i] + $arr[$j] == $sum)
echo "(", $arr[$i], ", ",
$arr[$j], ")", "\n";
}
// Driver Code
$arr = array (1, 5, 7, -1, 5);
$n = sizeof($arr);
$sum = 6;
printPairs($arr, $n, $sum);
// This code is contributed by m_kit
?>
Python3
# Python 3 implementation
# of simple method to find
# print pairs with given sum.
# Returns number of pairs
# in arr[0..n-1] with sum
# equal to 'sum'
def printPairs(arr, n, sum):
# count = 0
# Consider all possible
# pairs and check their sums
for i in range(0, n):
for j in range(i + 1, n):
if (arr[i] + arr[j] == sum):
print("(", arr[i],
", ", arr[j],
")", sep="")
# Driver Code
arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
printPairs(arr, n, sum)
# This code is contributed
# by Smitha
Time Complexity: O(N2 logN) where N is the number of elements.
Auxiliary Space: O(N)
Print all pairs with given sum using Two Pointers
The idea is to sort the array and then utilize a two-pointer approach to efficiently explore the array while using map (m
) to find unique pairs in the array with given sum.
Follow the steps to solve the problem:
- Sort the elements in ascending order to facilitate a two-pointer traversal.
- Set low and high pointers at the start and end of the array, respectively. Create an unordered map (
m
) to track unique pairs. - Use a while loop to iterate until the low pointer is less than the high pointer.
- Check if the sum of elements at low and high pointers equals the specified target. If yes, print the pair if at least one element is not already in the map. Update the map accordingly.
- Adjust the pointers based on the comparison of the sum with the target. Continue this process until all possible pairs are considered.
Below is the implementation of above approach:
C++
// C++ code to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
void pairedElements(int arr[], int sum, int n)
{
// Initialize pointers
int low = 0;
int high = n - 1;
// Map to track unique pairs
unordered_map<int, int> m;
// Iterate with two pointers
while (low < high) {
// Check if sum equals the target
if (arr[low] + arr[high] == sum) {
// Print pair if elements are not already in the map
if(m.find(arr[low]) == m.end() || m.find(arr[high])==m.end())
{
cout << "The pair is : (" << arr[low] << ", "
<< arr[high] << ")" << endl;
m[arr[low]]++;
m[arr[high]]++;
}
low++;
high--;
}
// Adjust pointers based on sum comparison
else if (arr[low] + arr[high] > sum) {
high--;
}
else {
low++;
}
}
}
// Driver code
int main()
{
int arr[] = { 2, 3, 4, -2, 6, 8, 3, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
// Sort the array
sort(arr, arr + n);
// Call the pairedElements function
pairedElements(arr, 6, n);
}
Java
import java.util.*;
public class PairedElements {
public static void pairedElements(int[] arr, int targetSum) {
// Sort the array
Arrays.sort(arr);
// Initialize pointers
int low = 0;
int high = arr.length - 1;
// Map to track unique pairs
Map<Integer, Boolean> uniquePairs = new HashMap<>();
// Iterate with two pointers
while (low < high) {
// Check if sum equals the target
if (arr[low] + arr[high] == targetSum) {
// Print pair if elements are not already in the map
if (!uniquePairs.containsKey(arr[low]) || !uniquePairs.containsKey(arr[high])) {
System.out.println("The pair is : (" + arr[low] + ", " + arr[high] + ")");
uniquePairs.put(arr[low], true);
uniquePairs.put(arr[high], true);
}
low++;
high--;
} else if (arr[low] + arr[high] > targetSum) { // Adjust pointers based on sum comparison
high--;
} else {
low++;
}
}
}
// Driver code
public static void main(String[] args) {
int[] arr = {2, 3, 4, -2, 6, 8, 3, 3};
int targetSum = 6;
// Call the pairedElements function
pairedElements(arr, targetSum);
}
}
JavaScript
function pairedElements(arr, targetSum) {
// Sort the array
arr.sort((a, b) => a - b);
// Initialize pointers
let low = 0;
let high = arr.length - 1;
// Object to track unique pairs
const uniquePairs = {};
// Iterate with two pointers
while (low < high) {
// Check if sum equals the target
if (arr[low] + arr[high] === targetSum) {
// Print pair if elements are not already in the object
if (!uniquePairs[arr[low]] || !uniquePairs[arr[high]]) {
console.log("The pair is : (" + arr[low] + ", " + arr[high] + ")");
uniquePairs[arr[low]] = true;
uniquePairs[arr[high]] = true;
}
low++;
high--;
} else if (arr[low] + arr[high] > targetSum) { // Adjust pointers based on sum comparison
high--;
} else {
low++;
}
}
}
// Driver code
const arr = [2, 3, 4, -2, 6, 8, 3, 3];
const targetSum = 6;
// Call the pairedElements function
pairedElements(arr, targetSum);
Python3
def paired_elements(arr, target_sum):
# Sort the array
arr.sort()
# Initialize pointers
low = 0
high = len(arr) - 1
# Dictionary to track unique pairs
unique_pairs = {}
# Iterate with two pointers
while low < high:
# Check if sum equals the target
if arr[low] + arr[high] == target_sum:
# Print pair if elements are not already in the dictionary
if arr[low] not in unique_pairs or arr[high] not in unique_pairs:
print("The pair is : (", arr[low], ", ", arr[high], ")")
unique_pairs[arr[low]] = True
unique_pairs[arr[high]] = True
low += 1
high -= 1
# Adjust pointers based on sum comparison
elif arr[low] + arr[high] > target_sum:
high -= 1
else:
low += 1
# Driver code
if __name__ == "__main__":
arr = [2, 3, 4, -2, 6, 8, 3, 3]
target_sum = 6
# Call the paired_elements function
paired_elements(arr, target_sum)
OutputThe pair is : (-2, 8)
The pair is : (2, 4)
The pair is : (3, 3)
Time Complexity: O(N*logN) where N is the number of elements
Auxiliary Space: O(N)
Print all pairs with given sum using Hashing
The idea is to use unordered map to find and print all unique pairs in an array whose sum is equal to a specified target. The (unordered map) should be used efficiently keep track of elements encountered during traversal to print unique pairs.
Follow the steps to solve the problem:
- Create an unordered map (
m
) to store the counts of elements encountered in the array. - Iterate through the array elements.
- For each element, calculate its complement by subtracting it from the target sum.
- Check if the complement is present in the map. If yes, print the pair if it is unique, considering the case when the complement is equal to the current array element.
- Update the map with the current element’s count.
Below is the implementation of above approach:
C++
// C++ implementation of a simple method to
// find the count of pairs with a given sum.
#include <bits/stdc++.h>
using namespace std;
// Function to print pairs with the given sum
void printPairs(int arr[], int n, int sum) {
// Store counts of all elements in map m
unordered_map<int, int> m;
// Traverse through all elements
for (int i = 0; i < n; i++) {
// Search if a pair can be formed with arr[i].
int rem = sum - arr[i];
if (rem == arr[i]) {
// Check if the complement is in the map and occurs only once
if (m.find(rem) != m.end() && m[rem] == 1) {
cout << "(" << rem << ", " << arr[i] << ")" << endl;
}
} else if (m.find(rem) != m.end() && m.find(arr[i]) == m.end()) {
// Check if the complement is in the map and the current element is not in the map
cout << "(" << rem << ", " << arr[i] << ")" << endl;
}
m[arr[i]]++; // Update the map with the current element's count
}
}
// Driver function to test the above function
int main() {
int arr[] = {1, 5, 7, -1, 5, 3, 3, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 6;
printPairs(arr, n, sum);
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
public class PairSum {
// Function to print pairs with the given sum
static void printPairs(int[] arr, int n, int sum) {
// Store counts of all elements in map m
Map<Integer, Integer> m = new HashMap<>();
// Traverse through all elements
for (int i = 0; i < n; i++) {
// Search if a pair can be formed with arr[i].
int rem = sum - arr[i];
if (rem == arr[i]) {
// Check if the complement is in the map and occurs only once
if (m.containsKey(rem) && m.get(rem) == 1) {
System.out.println("(" + rem + ", " + arr[i] + ")");
}
} else if (m.containsKey(rem) && !m.containsKey(arr[i])) {
// Check if the complement is in the map and the current element is not in the map
System.out.println("(" + rem + ", " + arr[i] + ")");
}
m.put(arr[i], m.getOrDefault(arr[i], 0) + 1); // Update the map with the current element's count
}
}
// Driver function to test the above function
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5, 3, 3, 3};
int n = arr.length;
int sum = 6;
printPairs(arr, n, sum);
}
}
Python3
def printPairs(arr, n, sum):
# Store counts of all elements in map m
m = {}
# Traverse through all elements
for i in range(n):
# Search if a pair can be formed with arr[i].
rem = sum - arr[i]
if rem == arr[i]:
# Check if the complement is in the map and occurs only once
if m.get(rem, 0) == 1:
print(f"({rem}, {arr[i]})")
elif rem in m and arr[i] not in m:
# Check if the complement is in the map and the current element is not in the map
print(f"({rem}, {arr[i]})")
m[arr[i]] = m.get(arr[i], 0) + 1 # Update the map with the current element's count
# Driver function to test the above function
arr = [1, 5, 7, -1, 5, 3, 3, 3]
n = len(arr)
sum_val = 6
printPairs(arr, n, sum_val)
Output(1, 5)
(7, -1)
(3, 3)
Time Complexity: O(N) where N is the number of elements in array
Auxiliary Space: O(N) due to map.
Last Updated :
28 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...