2 Sum - Count distinct pairs with given sum
Last Updated :
23 Jul, 2025
Given an array arr[] of size n and an integer target, the task is to count the number of distinct pairs in the array whose sum is equal to target.
Examples:
Input: arr[] = { 5, 6, 5, 7, 7, 8 }, target = 13
Output: 2
Explanation: Distinct pairs with sum equal to 13 are (5, 8) and (6, 7).
Input: arr[] = { 2, 6, 7, 1, 8, 3 }, target = 10
Output: 2
Explanation: Distinct pairs with sum equal to 10 are (2, 8) and (7, 3).
[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 count all distinct pairs with
// given target using three nested loops
#include <bits/stdc++.h>
using namespace std;
// Function to find all possible pairs with the sum target
int cntDistinctPairs(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) {
vector<int> cur = {arr[i], arr[j]};
sort(cur.begin(), cur.end());
// 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.size();
}
int main() {
vector<int> arr = { 5, 6, 5, 7, 7, 8 };
int target = 13;
cout << cntDistinctPairs(arr, target);
return 0;
}
Java
// Java program to count all distinct pairs with
// given target using three nested loops
import java.util.ArrayList;
import java.util.Arrays;
class GfG {
// Function to find all possible pairs with the sum target
static int cntDistinctPairs(int[] arr, int target) {
ArrayList<int[]> 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[] cur = {arr[i], arr[j]};
Arrays.sort(cur);
// Making sure that all pairs with
// target sum are distinct
boolean isDistinct = true;
for (int[] pair : res) {
if (Arrays.equals(pair, cur)) {
isDistinct = false;
break;
}
}
if (isDistinct) {
res.add(cur);
}
}
}
}
return res.size();
}
public static void main(String[] args) {
int[] arr = {5, 6, 5, 7, 7, 8};
int target = 13;
System.out.println(cntDistinctPairs(arr, target));
}
}
Python
# Python program to count all distinct pairs with
# given target using three nested loops
def cntDistinctPairs(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 = [arr[i], arr[j]]
cur.sort()
# Making sure that all pairs with target
# sum are distinct
if cur not in res:
res.append(cur)
return len(res)
if __name__ == "__main__":
arr = [5, 6, 5, 7, 7, 8]
target = 13
print(cntDistinctPairs(arr, target))
C#
// C# program to count all distinct pairs with
// given target using three nested loops
using System;
using System.Collections.Generic;
class GfG {
// Function to find all possible pairs with the sum target
static int cntDistinctPairs(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) {
List<int> cur = new List<int> { arr[i], arr[j] };
cur.Sort();
// Making sure that all pairs with target
// sum are distinct
if (!res.Exists(pair => pair[0] == cur[0] && pair[1] == cur[1])) {
res.Add(cur);
}
}
}
}
return res.Count;
}
static void Main() {
int[] arr = { 5, 6, 5, 7, 7, 8 };
int target = 13;
Console.WriteLine(cntDistinctPairs(arr, target));
}
}
JavaScript
// JavaScript program to count all distinct pairs with
// given target using three nested loops
function cntDistinctPairs(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 cur = [arr[i], arr[j]];
cur.sort((a, b) => a - b);
// 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.length;
}
const arr = [5, 6, 5, 7, 7, 8];
const target = 13;
console.log(cntDistinctPairs(arr, target));
Time Complexity: O(n^3), where n is size of arr[].
Auxiliary Space: O(n^2), as in the worst case we can have (n * (n - 1))/2 pairs in the result.
[Better Approach] Sorting and Two Pointer technique - O(n*log n) Time and O(1) Space
The idea is to sort the array and use two pointers at the beginning and end of the array. If the sum of the elements at these pointers equals target, we update the pair counter and skip duplicates to ensure they are distinct. If the sum is less than the target, we move the left pointer towards right and if sum is greater than target, we move the right pointer towards left. This continues until all pairs are checked, giving us the total count of distinct pairs.
C++
// C++ program to count all distinct pairs with given
// target using sorting and two pointer technique
#include <bits/stdc++.h>
using namespace std;
// Function to count distinct pairs whose sum is
// equal to target
int cntDistinctPairs(vector<int> &arr, int target) {
int res = 0;
int n = arr.size();
sort(arr.begin(), arr.end());
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] + arr[right] == target) {
res++;
// Skip consecutive duplicate array elements
while (left < right && arr[left] == arr[left + 1])
left++;
// Skip consecutive duplicate array elements
while (left < right && arr[right] == arr[right - 1])
right--;
left++;
right--;
}
else if (arr[left] + arr[right] < target)
left++;
else
right--;
}
return res;
}
int main() {
vector<int> arr = { 5, 6, 5, 7, 7, 8 };
int target = 13;
cout << cntDistinctPairs(arr, target);
return 0;
}
C
// C program to count all distinct pairs with given
// target using sorting and two pointer technique
#include <stdio.h>
// Function to compare two integers (used for sorting)
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
// Function to count distinct pairs whose sum is
// equal to target
int cntDistinctPairs(int arr[], int n, int target) {
int res = 0;
qsort(arr, n, sizeof(int), compare);
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] + arr[right] == target) {
res++;
// Skip consecutive duplicate array elements
while (left < right && arr[left] == arr[left + 1])
left++;
// Skip consecutive duplicate array elements
while (left < right && arr[right] == arr[right - 1])
right--;
left++;
right--;
}
else if (arr[left] + arr[right] < target)
left++;
else
right--;
}
return res;
}
int main() {
int arr[] = { 5, 6, 5, 7, 7, 8 };
int target = 13;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", cntDistinctPairs(arr, n, target));
return 0;
}
Java
// Java program to count all distinct pairs with given
// target using sorting and two pointer technique
import java.util.Arrays;
class GfG {
// Function to count distinct pairs whose sum is
// equal to target
static int cntDistinctPairs(int[] arr, int target) {
int res = 0;
int n = arr.length;
Arrays.sort(arr);
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] + arr[right] == target) {
res++;
// Skip consecutive duplicate array elements
while (left < right && arr[left] == arr[left + 1])
left++;
// Skip consecutive duplicate array elements
while (left < right && arr[right] == arr[right - 1])
right--;
left++;
right--;
}
else if (arr[left] + arr[right] < target)
left++;
else
right--;
}
return res;
}
public static void main(String[] args) {
int[] arr = { 5, 6, 5, 7, 7, 8 };
int target = 13;
System.out.println(cntDistinctPairs(arr, target));
}
}
Python
# Python program to count all distinct pairs with given
# target using sorting and two pointer technique
def cntDistinctPairs(arr, target):
res = 0
n = len(arr)
arr.sort()
left = 0
right = n - 1
while left < right:
if arr[left] + arr[right] == target:
res += 1
# Skip consecutive duplicate array elements
while left < right and arr[left] == arr[left + 1]:
left += 1
# Skip consecutive duplicate array elements
while left < right and arr[right] == arr[right - 1]:
right -= 1
left += 1
right -= 1
elif arr[left] + arr[right] < target:
left += 1
else:
right -= 1
return res
if __name__ == "__main__":
arr = [5, 6, 5, 7, 7, 8]
target = 13
print(cntDistinctPairs(arr, target))
C#
// C# program to count all distinct pairs with given
// target using sorting and two pointer technique
using System;
using System.Collections.Generic;
class GfG {
// Function to count distinct pairs whose sum is
// equal to target
static int cntDistinctPairs(int[] arr, int target) {
int res = 0;
int n = arr.Length;
Array.Sort(arr);
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] + arr[right] == target) {
res++;
// Skip consecutive duplicate array elements
while (left < right && arr[left] == arr[left + 1])
left++;
// Skip consecutive duplicate array elements
while (left < right && arr[right] == arr[right - 1])
right--;
left++;
right--;
}
else if (arr[left] + arr[right] < target)
left++;
else
right--;
}
return res;
}
static void Main() {
int[] arr = { 5, 6, 5, 7, 7, 8 };
int target = 13;
Console.WriteLine(cntDistinctPairs(arr, target));
}
}
JavaScript
// JavaScript program to count all distinct pairs with given
// target using sorting and two pointer technique
function cntDistinctPairs(arr, target) {
let res = 0;
let n = arr.length;
arr.sort((a, b) => a - b);
let left = 0, right = n - 1;
while (left < right) {
if (arr[left] + arr[right] === target) {
res++;
// Skip consecutive duplicate array elements
while (left < right && arr[left] === arr[left + 1])
left++;
// Skip consecutive duplicate array elements
while (left < right && arr[right] === arr[right - 1])
right--;
left++;
right--;
}
else if (arr[left] + arr[right] < target)
left++;
else
right--;
}
return res;
}
const arr = [5, 6, 5, 7, 7, 8];
const target = 13;
console.log(cntDistinctPairs(arr, target));
Time Complexity: O(n * log(n)), where n is size of arr[]
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;
int cntDistinctPairs(vector<int> &arr, int target) {
int res = 0;
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++;
}
// 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) {
res++;
}
// Add the current element in the hash map
freq[arr[i]]++;
}
return res;
}
int main() {
vector<int> arr = {5, 6, 5, 7, 7, 8};
int target = 13;
cout << cntDistinctPairs(arr, target);
return 0;
}
Java
// Java program to count all distinct pairs with given
// sum using Hash Map
import java.util.HashMap;
import java.util.Map;
class GfG {
static int cntDistinctPairs(int[] arr, int target) {
int res = 0;
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++;
}
// 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) {
res++;
}
// Add the current element in the hash map
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
}
return res;
}
public static void main(String[] args) {
int[] arr = {5, 6, 5, 7, 7, 8};
int target = 13;
System.out.println(cntDistinctPairs(arr, target));
}
}
Python
# Python program to count all distinct pairs with given
# sum using Hash Map
def cntDistinctPairs(arr, target):
res = 0
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 += 1
# 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:
res += 1
# Add the current element in the hash map
freq[arr[i]] = freq.get(arr[i], 0) + 1
return res
if __name__ == "__main__":
arr = [5, 6, 5, 7, 7, 8]
target = 13
print(cntDistinctPairs(arr, target))
C#
// C# program to count all distinct pairs with given
// sum using Hash Map
using System;
using System.Collections.Generic;
class GfG {
static int cntDistinctPairs(List<int> arr, int target) {
int res = 0;
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++;
}
// 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) {
res++;
}
// Add the current element in the hash map
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
return res;
}
static void Main(string[] args) {
List<int> arr = new List<int> { 5, 6, 5, 7, 7, 8 };
int target = 13;
Console.WriteLine(cntDistinctPairs(arr, target));
}
}
JavaScript
// JavaScript program to count all distinct pairs with given
// sum using Hash Map
function cntDistinctPairs(arr, target) {
const st = new Set();
const seen = new Set();
let res = 0;
for (let i = 0; i < arr.length; i++) {
const complement = target - arr[i];
// If complement of current element exist in set
// and is not previously seen then count this pair
if (st.has(complement) && !seen.has(arr[i])) {
res++;
seen.add(arr[i]);
seen.add(complement);
}
// Add the current element in the hash map
st.add(arr[i]);
}
return res;
}
const arr = [5, 6, 5, 7, 7, 8];
const target = 13;
console.log(cntDistinctPairs(arr, target));
Time Complexity: O(n), where n is size of arr[]
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