2 Sum – All distinct pairs with given sum
Last Updated :
11 Jul, 2025
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 .
Examples:
Input: arr[] = {1, 5, 7, -1, 5}, target= 6
Output: {{1, 5}, {-1, 7}}
Explanation: There are only two pairs that add up to 6: {1, 5} and {-1, 7}.
Input: arr[] = {1, 9, -1, 8, 6}, target = 4
Output: {{}}
Explanation: No pairs add up to 4.
[Naive Approach] Using Three Nested Loops - O(n^3) Time and O(1) Space
A simple approach is to generate all possible pairs using two nested loops and if they add up to target value, then for each such pair check whether this pair already exists in the result or not.
C++
// C++ program to print all distinct pairs
// with given sum using three nested loops
#include <bits/stdc++.h>
using namespace std;
// Function to find all possible pairs with the sum target
vector<vector<int>> distinctPairs(vector<int> &arr, int target) {
vector<vector<int>> res;
int n = arr.size();
// Iterating over all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = min(arr[i], arr[j]);
int second = max(arr[i], arr[j]);
vector<int> cur = {first, second};
// Making sure that all pairs with target
// sum are distinct
if(find(res.begin(), res.end(), cur) == res.end())
res.push_back(cur);
}
}
}
return res;
}
int main() {
vector<int> arr = {1, 5, 7, -1, 5};
int target = 6;
vector<vector<int>> res = distinctPairs(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i][0] << " " << res[i][1] << endl;
return 0;
}
C
// C program to print all distinct pairs
// with given sum using three nested loops
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Function to find all possible pairs with the sum target
void distinctPairs(int arr[], int n, int target) {
int res[1000][2];
int res_count = 0;
// Iterating over all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = arr[i] < arr[j] ? arr[i] : arr[j];
int second = arr[i] > arr[j] ? arr[i] : arr[j];
bool isDistinct = true;
// Making sure that all pairs with target
// sum are distinct
for (int k = 0; k < res_count; k++) {
if (res[k][0] == first && res[k][1] == second) {
isDistinct = false;
break;
}
}
if (isDistinct) {
res[res_count][0] = first;
res[res_count][1] = second;
res_count++;
}
}
}
}
for (int i = 0; i < res_count; i++) {
printf("%d %d\n", res[i][0], res[i][1]);
}
}
int main() {
int arr[] = {1, 5, 7, -1, 5};
int target = 6;
int n = sizeof(arr) / sizeof(arr[0]);
distinctPairs(arr, n, target);
return 0;
}
Java
// Java program to print all distinct pairs
// with given sum using three nested loops
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
class GfG {
// Function to find all possible pairs with the sum target
static List<List<Integer>> distinctPairs(int[] arr, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = arr.length;
// Iterating over all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = Math.min(arr[i], arr[j]);
int second = Math.max(arr[i], arr[j]);
List<Integer> cur = new ArrayList<>
(Arrays.asList(first, second));
// Making sure that all pairs with target
// sum are distinct
if (!res.contains(cur))
res.add(cur);
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int target = 6;
List<List<Integer>> res = distinctPairs(arr, target);
for (List<Integer> pair : res)
System.out.println(pair.get(0) + " " + pair.get(1));
}
}
Python
# Python program to print all distinct pairs
# with given sum using three nested loops
def distinctPairs(arr, target):
res = []
n = len(arr)
# Iterating over all possible pairs
for i in range(n):
for j in range(i + 1, n):
if arr[i] + arr[j] == target:
cur = [min(arr[i], arr[j]), max(arr[i], arr[j])]
# Making sure that all pairs with target
# sum are distinct
if cur not in res:
res.append(cur)
return res
if __name__ == "__main__":
arr = [1, 5, 7, -1, 5]
target = 6
res = distinctPairs(arr, target)
for pair in res:
print(pair[0], pair[1])
C#
// C# program to print all distinct pairs
// with given sum using three nested loops
using System;
using System.Collections.Generic;
class GfG {
// Function to find all possible pairs with the sum target
static List<List<int>> distinctPairs(int[] arr, int target) {
List<List<int>> res = new List<List<int>>();
int n = arr.Length;
// Iterating over all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = Math.Min(arr[i], arr[j]);
int second = Math.Max(arr[i], arr[j]);
List<int> cur = new List<int> { first, second };
// Making sure that all pairs with target
// sum are distinct
if (!res.Exists(x => x[0] == cur[0] && x[1] == cur[1]))
res.Add(cur);
}
}
}
return res;
}
static void Main() {
int[] arr = { 1, 5, 7, -1, 5 };
int target = 6;
List<List<int>> res = distinctPairs(arr, target);
foreach (var pair in res)
Console.WriteLine($"{pair[0]} {pair[1]}");
}
}
JavaScript
// JavaScript program to print all distinct pairs
// with given sum using three nested loops
// Function to find all possible pairs with the sum target
function distinctPairs(arr, target) {
let res = [];
let n = arr.length;
// Iterating over all possible pairs
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[i] + arr[j] === target) {
let first = Math.min(arr[i], arr[j]);
let second = Math.max(arr[i], arr[j]);
let cur = [first, second];
// Making sure that all pairs with target sum are distinct
if (!res.some(pair => pair[0] === cur[0] && pair[1] === cur[1])) {
res.push(cur);
}
}
}
}
return res;
}
let arr = [1, 5, 7, -1, 5];
let target = 6;
let res = distinctPairs(arr, target);
for (let i = 0; i < res.length; i++)
console.log(res[i][0] + " " + res[i][1]);
Time Complexity: O(n^3), for using three nested loops
Auxiliary Space: O(1),
[Better Approach 1] Using Hash Set - O(n^2) Time and O(n) Space
Better approach is to generate all possible pairs using two nested loops and check if they add up to target value, then store them in a hash set to eliminate duplicate pairs.
C++
// C++ progam to find all distinct pairs with given sum
// using two nested loops and HashSet
#include <bits/stdc++.h>
using namespace std;
//Function to find all possible pairs with the sum target
vector<vector<int>> distinctPairs(vector<int> &arr, int target) {
vector<vector<int>> res;
int n = arr.size();
// Ideally we should us an unordered_set here, but C++
// does not support vector as a key in an unordered_set
// So we have used set to keep the code simple. However
// set internally uses Red Black Tree and has O(Log n)
// time complexities for operations
set<vector<int>> st;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = min(arr[i], arr[j]);
int second = max(arr[i], arr[j]);
vector<int> cur = {first, second};
// If the pair is not already in the set, add it
if (st.find(cur) == st.end()) {
res.push_back(cur);
st.insert(cur);
}
}
}
}
return res;
}
int main() {
vector<int> arr = {1, 5, 7, -1, 5};
int target = 6;
vector<vector<int>> res = distinctPairs(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i][0] << " " << res[i][1] << endl;
return 0;
}
Java
// Java program to find the distinct pairs with
// given sum using two nested loops and HashSet
import java.util.*;
class GfG {
// Function to find all possible pairs with the sum target
static List<List<Integer>> distinctPairs(int[] arr, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = arr.length;
// Set to handle duplicates using sorted pairs
Set<List<Integer>> st = new HashSet<>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = Math.min(arr[i], arr[j]);
int second = Math.max(arr[i], arr[j]);
List<Integer> cur = new ArrayList<>
(Arrays.asList(first, second));
// If the pair is not already in the set, add it
if (!st.contains(cur)) {
res.add(cur);
st.add(cur);
}
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int target = 6;
List<List<Integer>> res = distinctPairs(arr, target);
for (List<Integer> pair : res) {
System.out.println(pair.get(0) + " " + pair.get(1));
}
}
}
Python
# Python program to find the distinct pairs with
# given sum using two nested loops and set
def distinctPairs(arr, target):
res = []
n = len(arr)
# Set to handle duplicates using sorted pairs
st = set()
for i in range(n):
for j in range(i + 1, n):
if arr[i] + arr[j] == target:
first = min(arr[i], arr[j])
second = max(arr[i], arr[j])
cur = (first, second)
# If the pair is not already in the set, add it
if cur not in st:
res.append([first, second])
st.add(cur)
return res
if __name__ == "__main__":
arr = [1, 5, 7, -1, 5]
target = 6
res = distinctPairs(arr, target)
for pair in res:
print(pair[0], pair[1])
C#
// C# program to find the distinct pairs with
// given sum using two nested loops and HashSet
using System;
using System.Collections.Generic;
class GfG {
// Function to find all possible pairs with the sum target
static List<List<int>> distinctPairs(int[] arr, int target) {
List<List<int>> res = new List<List<int>>();
int n = arr.Length;
// Set to handle duplicates using sorted pairs
HashSet<(int, int)> st = new HashSet<(int, int)>();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
int first = Math.Min(arr[i], arr[j]);
int second = Math.Max(arr[i], arr[j]);
// If the pair is not already in the set, add it
var cur = (first, second);
if (!st.Contains(cur)) {
res.Add(new List<int> { first, second });
st.Add(cur);
}
}
}
}
return res;
}
static void Main() {
int[] arr = { 1, 5, 7, -1, 5 };
int target = 6;
List<List<int>> res = distinctPairs(arr, target);
foreach (var pair in res) {
Console.WriteLine(pair[0] + " " + pair[1]);
}
}
}
JavaScript
// JavaScript program to find the distinct pairs with
// given sum using two nested loops and Set
function distinctPairs(arr, target) {
let res = [];
let n = arr.length;
// Set to handle duplicates using sorted pairs
let st = new Set();
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[i] + arr[j] === target) {
let first = Math.min(arr[i], arr[j]);
let second = Math.max(arr[i], arr[j]);
let cur = [first, second];
let curString = cur.toString();
// If the pair is not already in the set, add it
if (!st.has(curString)) {
res.push(cur);
st.add(curString);
}
}
}
}
return res;
}
let arr = [1, 5, 7, -1, 5];
let target = 6;
let res = distinctPairs(arr, target);
res.forEach(pair => console.log(pair[0], pair[1]));
Time Complexity: O(n²), for using two nested loops.
Auxiliary Space: O(n), for hash set.
[Better Approach 2] Using Two Pointers Technique – O(n*logn) Time and O(1) Space
The idea is to sort the array and use two pointers technique to find all the pairs. Initialize two pointers at the beginning and end of the array. Now, compare the sum of elements at these pointers:
- If sum = target, store the pair and skip duplicates to ensure they are distinct.
- If sum < target, we move the left pointer towards right.
- If sum > target, we move the right pointer towards left.
This continues until all pairs are checked, giving us all the distinct pairs.
C++
// C++ program to find all distinct pairs with given sum
// using sorting and two pointers technique
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> distinctPairs(vector<int> &arr, int target) {
vector<vector<int>> res;
int n = arr.size();
sort(arr.begin(), arr.end());
int left = 0;
int right = n - 1;
while (left < right) {
// Skip Duplicates
if (left > 0 && arr[left] == arr[left - 1]) {
left++;
continue;
}
if (right < n - 1 && arr[right] == arr[right + 1]) {
right--;
continue;
}
// Check if sum equals the target
if (arr[left] + arr[right] == target) {
res.push_back({arr[left], arr[right]});
left++;
right--;
}
else if (arr[left] + arr[right] > target)
right--;
else
left++;
}
return res;
}
int main() {
vector<int> arr = {1, 5, 7, -1, 5};
int target = 6;
vector<vector<int>> res = distinctPairs(arr, target);
for (int i = 0; i < res.size(); i++)
cout << res[i][0] << " " << res[i][1] << endl;
return 0;
}
C
// C program to find all distinct pairs with given sum
// using sorting and two pointers technique
#include <stdio.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
void distinctPairs(int arr[], int n, int target) {
qsort(arr, n, sizeof(int), compare);
int left = 0;
int right = n - 1;
while (left < right) {
// Skip Duplicates
if (left > 0 && arr[left] == arr[left - 1]) {
left++;
continue;
}
if (right < n - 1 && arr[right] == arr[right + 1]) {
right--;
continue;
}
// Check if sum equals the target
if (arr[left] + arr[right] == target) {
printf("%d %d\n", arr[left], arr[right]);
left++;
right--;
}
else if (arr[left] + arr[right] > target) {
right--;
}
else {
left++;
}
}
}
int main() {
int arr[] = {1, 5, 7, -1, 5};
int target = 6;
int n = sizeof(arr) / sizeof(arr[0]);
distinctPairs(arr, n, target);
return 0;
}
Java
// Java program to find all distinct pairs with given sum
// using sorting and two pointers technique
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class GfG {
static List<List<Integer>> distinctPairs(int[] arr, int target) {
List<List<Integer>> res = new ArrayList<>();
// Initialize pointers
int l = 0;
int r = arr.length - 1;
while (l < r) {
// Avoiding duplicates
if (l > 0 && arr[l] == arr[l - 1]) {
l++;
continue;
}
if (r < arr.length - 1 && arr[r] == arr[r + 1]) {
r--;
continue;
}
// Check if sum equals the target
if (arr[l] + arr[r] == target) {
res.add(Arrays.asList(arr[l], arr[r]));
l++;
r--;
}
else if (arr[l] + arr[r] > target) {
r--;
}
else {
l++;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int target = 6;
Arrays.sort(arr);
List<List<Integer>> res = distinctPairs(arr, target);
for (List<Integer> pair : res) {
System.out.println(pair.get(0) + " " + pair.get(1));
}
}
}
Python
# Python program to find all distinct pairs with given sum
# using sorting and two pointers technique
def distinctPairs(arr, target):
res = []
n = len(arr)
arr.sort()
left = 0
right = n - 1
while left < right:
# Skip Duplicates
if left > 0 and arr[left] == arr[left - 1]:
left += 1
continue
if right < n - 1 and arr[right] == arr[right + 1]:
right -= 1
continue
# Check if sum equals the target
if arr[left] + arr[right] == target:
res.append([arr[left], arr[right]])
left += 1
right -= 1
elif arr[left] + arr[right] > target:
right -= 1
else:
left += 1
return res
if __name__ == "__main__":
arr = [1, 5, 7, -1, 5]
target = 6
res = distinctPairs(arr, target)
for pair in res:
print(pair[0], pair[1])
C#
// C# program to find all distinct pairs with given sum
// using sorting and two pointers technique
using System;
using System.Collections.Generic;
class GfG {
static List<List<int>> DistinctPairs(int[] arr, int target) {
List<List<int>> res = new List<List<int>>();
int n = arr.Length;
Array.Sort(arr);
int left = 0;
int right = n - 1;
while (left < right) {
// Skip Duplicates
if (left > 0 && arr[left] == arr[left - 1]) {
left++;
continue;
}
if (right < n - 1 && arr[right] == arr[right + 1]) {
right--;
continue;
}
// Check if sum equals the target
if (arr[left] + arr[right] == target) {
res.Add(new List<int> { arr[left], arr[right] });
left++;
right--;
}
else if (arr[left] + arr[right] > target)
right--;
else
left++;
}
return res;
}
static void Main() {
int[] arr = { 1, 5, 7, -1, 5 };
int target = 6;
List<List<int>> res = DistinctPairs(arr, target);
foreach (var pair in res) {
Console.WriteLine(pair[0] + " " + pair[1]);
}
}
}
JavaScript
// JavaScript program to find all distinct pairs with given sum
// using sorting and two pointers technique
function distinctPairs(arr, target) {
let res = [];
let n = arr.length;
arr.sort((a, b) => a - b);
let left = 0;
let right = n - 1;
while (left < right) {
// Skip Duplicates
if (left > 0 && arr[left] === arr[left - 1]) {
left++;
continue;
}
if (right < n - 1 && arr[right] === arr[right + 1]) {
right--;
continue;
}
// Check if sum equals the target
if (arr[left] + arr[right] === target) {
res.push([arr[left], arr[right]]);
left++;
right--;
}
else if (arr[left] + arr[right] > target)
right--;
else
left++;
}
return res;
}
const arr = [1, 5, 7, -1, 5];
const target = 6;
const res = distinctPairs(arr, target);
for (let i = 0; i < res.length; i++)
console.log(res[i][0] + " " + res[i][1]);
Time Complexity: O(n*log(n)), for sorting the array
Auxiliary Space: O(1)
[Expected Approach] Using Hash Map – O(n) Time and O(n) Space
The idea is to maintain a hash map to track how many times each element has occurred in the array so far. Traverse all the elements and for each element arr[i], check if the complement (target – arr[i]) already exists in the map, if it exists then we have found a pair whose sum is equal to target.
How to ensure that we don’t include duplicate pairs?
To ensure that we don’t include duplicate pairs, we can have two cases:
- If arr[i] == complement, then we check for exactly one occurrence of arr[i] before index i. If it occurs exactly once, then arr[i] can pair with itself and form a pair with sum = target. Also, if there is more than one occurrence of arr[i], then it means that the pair has already been counted previously, so this element forms a duplicate pair.
- If arr[i] != complement, then we check for at least one occurrence of complement and no occurrence of arr[i] before index i. If both the conditions are satisfied, then it means that arr[i] and complement forms a unique pair with sum = target.
C++
// C++ program to count all distinct pairs with given
// sum using Hash Map
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> distinctPairs(vector<int> &arr, int target) {
vector<vector<int>> res;
int n = arr.size();
// frequency map to store the frequency of all elements
unordered_map<int, int> freq;
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// If the complement is equal to arr[i], then there should
// be only one occurrence of complement in the hash map
if (complement == arr[i]) {
if (freq[complement] == 1)
res.push_back({arr[i], arr[i]});
}
// if complement is not equal to arr[i], then there should
// be at least one occurrence of complement and no occurrence
// of current element in the hash map
else if (freq[complement] > 0 && freq[arr[i]] == 0) {
int first = min(arr[i], complement);
int second = max(arr[i], complement);
res.push_back({first, second});
}
freq[arr[i]]++;
}
return res;
}
int main() {
vector<int> arr = {1, 5, 7, -1, 5};
int target = 6;
vector<vector<int>> res = distinctPairs(arr, target);
for(vector<int> &pair: res)
cout << pair[0] << " " << pair[1] << endl;
return 0;
}
Java
// Java program to find all distinct pairs
// with given sum using HashMap
import java.util.*;
class GfG {
static List<List<Integer>> distinctPairs(int[] arr, int target) {
List<List<Integer>> res = new ArrayList<>();
int n = arr.length;
// frequency map to store the frequency of all elements
Map<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// If the complement is equal to arr[i], then there should
// be only one occurrence of complement in the hash map
if (complement == arr[i]) {
if (freq.getOrDefault(complement, 0) == 1)
res.add(Arrays.asList(arr[i], arr[i]));
}
// if complement is not equal to arr[i], then there should
// be at least one occurrence of complement and no occurrence
// of current element in the hash map
else if (freq.getOrDefault(complement, 0) > 0
&& freq.getOrDefault(arr[i], 0) == 0) {
int first = Math.min(arr[i], complement);
int second = Math.max(arr[i], complement);
res.add(Arrays.asList(first, second));
}
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int target = 6;
List<List<Integer>> res = distinctPairs(arr, target);
for (List<Integer> pair : res) {
System.out.println(pair.get(0) + " " + pair.get(1));
}
}
}
Python
# Python progam to find all distinct pairs
# with given sum using HashMap
def distinctPairs(arr, target):
res = []
n = len(arr)
# frequency map to store the frequency of all elements
freq = {}
for i in range(n):
complement = target - arr[i]
# If the complement is equal to arr[i], then there should
# be only one occurrence of complement in the hash map
if complement == arr[i]:
if freq.get(complement, 0) == 1:
res.append([arr[i], arr[i]])
# if complement is not equal to arr[i], then there should
# be at least one occurrence of complement and no occurrence
# of current element in the hash map
elif freq.get(complement, 0) > 0 and freq.get(arr[i], 0) == 0:
first = min(arr[i], complement)
second = max(arr[i], complement)
res.append([first, second])
freq[arr[i]] = freq.get(arr[i], 0) + 1
return res
if __name__ == "__main__":
arr = [1, 5, 7, -1, 5]
target = 6
res = distinctPairs(arr, target)
for pair in res:
print(pair[0], pair[1])
C#
// C# progam to find all distinct pairs
// with given sum using HashMap
using System;
using System.Collections.Generic;
class GfG {
static List<List<int>> distinctPairs(List<int> arr, int target) {
List<List<int>> res = new List<List<int>>();
int n = arr.Count;
// frequency map to store the frequency of all elements
Dictionary<int, int> freq = new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// If the complement is equal to arr[i], then there should
// be only one occurrence of complement in the hash map
if (complement == arr[i]) {
if (freq.GetValueOrDefault(complement, 0) == 1)
res.Add(new List<int> { arr[i], arr[i] });
}
// if complement is not equal to arr[i], then there should
// be at least one occurrence of complement and no occurrence
// of current element in the hash map
else if (freq.GetValueOrDefault(complement, 0) > 0
&& freq.GetValueOrDefault(arr[i], 0) == 0) {
int first = Math.Min(arr[i], complement);
int second = Math.Max(arr[i], complement);
res.Add(new List<int> { first, second });
}
freq[arr[i]] = freq.GetValueOrDefault(arr[i], 0) + 1;
}
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 1, 5, 7, -1, 5 };
int target = 6;
List<List<int>> res = distinctPairs(arr, target);
foreach (var pair in res)
Console.WriteLine($"{pair[0]} {pair[1]}");
}
}
JavaScript
// JavaScript progam to find all distinct pairs
// with given sum using HashMap
function distinctPairs(arr, target) {
let res = [];
let n = arr.length;
// frequency map to store the frequency of all elements
let freq = new Map();
for (let i = 0; i < n; i++) {
let complement = target - arr[i];
// If the complement is equal to arr[i], then there should
// be only one occurrence of complement in the hash map
if (complement === arr[i]) {
if (freq.get(complement) === 1)
res.push([arr[i], arr[i]]);
}
// if complement is not equal to arr[i], then there should
// be at least one occurrence of complement and no occurrence
// of current element in the hash map
else if (freq.get(complement) > 0 && freq.get(arr[i]) === undefined) {
let first = Math.min(arr[i], complement);
let second = Math.max(arr[i], complement);
res.push([first, second]);
}
freq.set(arr[i], (freq.get(arr[i]) || 0) + 1);
}
return res;
}
const arr = [1, 5, 7, -1, 5];
const target = 6;
const res = distinctPairs(arr, target);
for (const pair of res) {
console.log(pair[0], pair[1]);
}
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem