tutorialcup@gmail.com

Number of pairs with given sum

Arrays
Reverse Array
Pair Sum Equals Number
Floor and Ceil
Largest Sum Subarray
Missing Number
Odd Occuring Number
Sort by Frequency
First and Second Smallest
Majority Element
Difference between elements
Arrange Even and Odd
Closest Sum Elements
Distinct Elements
First Repeating Number
Common Elements in Arrays
Smallest Missing Number
Max Adjacent Sum
Find Occurrences of Number
Rotate Image
Distance Between Numbers
Pair with given difference
Product Array Puzzle
Replace Elements
First Repeating Element
Move Zeroes to End
Pythagorean Triplets
Maximum Average Subarray
Subarray Sum Equal to X
Leaders in Array
Largest Pair Sum
Segregate 0s 1s and 2s
Find Duplicates
Consecutive Elements Check
Triplet with given Sum
Binary Search in Sorted Array
Fixed point in sorted array
Reorder Elements by Indexes
Merging two sorted arrays
Find next greater number
Reorder array using given indexes
Count of triplets with sum less than given value
Merge two sorted arrays
Subarray and Subsequence
Rearrange array maximum minimum form
Find the lost element from a duplicated array
Count minimum steps to get the given array
Maximum element in an array which is increasing and then decreasing
Minimum number of jumps to reach the end of an array
Subarray with given sum
Length of Longest Increasing Subsequence
Smallest positive number missing unsorted array
The Celebrity Problem
Sorted subsequence of size 3
Partition Problem
Find pair with given difference
Maximum length of chain pairs
Four elements that sum to given
Maximum circular subarray sum
Count possible triangles
Longest Increasing Subsequence
Petrol Bunks Tour
Tug of War
Counting Sort
Maximum Repeating Number
Positive Negative Arrangement
Find a Peak element
Elements More Than n/k
Max Product Subsequence
Longest Bitonic subarray in an array
Number of smaller elements on right side
Implement two stacks in an array
Maximum sum increasing subsequence
Find the two numbers with odd occurrences in an unsorted array
Largest subarray with equal number of 0's and 1's
Maximum product subarray
Replace every element with the greatest on the right side in an array
Sorting a k sorted array
Find the row with maximum number of 1's
Shuffle a given array
Iterative Implementation of quick sort
Arrange given numbers to form the biggest number
Pancake sorting
Pancake sorting Problem
Maximum Subarray Sum using Divide and Conquer
Merge Overlapping Intervals
Stock Buy Sell to Maximize Profit
Sort Elements by frequency
Print all possible combinations of r elements in a given array of size n
Monotonically increasing function
Minimum element in a sorted and rotated array
Merge k Sorted Arrays
Flip Zeroes for Consecutive 1's
Least Average Subarray
Longest span with same sum in two binary arrays
Form minimum number from given sequence of D's and I's
Number of strictly increasing subarrays
Minimum difference between any two elements in an array
Number of pairs with given sum
Make Array Palindrome
Dynamic Programming, Longest Bitonic SubSequence

Given an array of integers and an input value, this function finds the number of pairs that has the sum equal to the given value

Example

INPUT :
arr[] = {1, 3, 7, -4, 2}
X = 3

OUTPUT :
The number of pairs with given sum 3 is 2 ie, {1,2} is one pair and {7, -4 } is one pair.

Time complexity : O(n^2)

In this algorithm, we will traverse each element and check whether their is another element in the arrray which can be added such that it is equal to given sum

Algorithm1

1. Simply create two loops

2. In the outer loop select an element till the end of the array ie, i =0 to n-1, where n is size

3. In the inner loop select an element from i+1 to n-1. ie, j= i+1 to n-1

4. Now, find the sum of the two elements ie, arr[i] +arr[j]. If it is equal to the given sum then increase the count of the number of pairs.

C++ Program

#include<iostream>

using namespace std;

int numPairs(int arr[], int X, int n) //this function returns the number of the pairs with sum X
{
	int i, j, sum, count =0;		  //sum to find the sum of the pair, count to count the number of pairs
	for(i=0;i<n-1;i++)                //finding all the pairs, if the pair sum is equal to given sum x, then we consider that pair
	{
		for (j = i+1; j < n; ++j)
		{
			sum = arr[i] + arr[j];
			if(sum == X)
			{
				count++;
			}			
		}
	}	
	return count;	
}

int main()
{
	int arr[] = {1, 5, 7, -4, 2};
	int X = 3;
	int n = sizeof(arr)/sizeof(arr[0]);
	int ans = numPairs(arr,X,n);
	cout<<"The number of pairs in the array with sum "<<X<<" is "<<ans;
	return 0;
}
Try It

Time Complexity : O(n)

Algorithm

1. Create a map to store the frequency of each number

Till the end of the array

  1. For each element check if it can be combined with any other element other than itself to     get the given sum . If found increment the count by 1. ie, count = count + m[sum - arr[i]]
  2. As every pair is counted twice, divide count by 2 and return.

C++ Program

#include <bits/stdc++.h>
#include <tr1/unordered_map>

using namespace std::tr1;
using namespace std;

int numPairs(int arr[], int X, int n) //this function returns the number of the pairs with sum X
{
	unordered_map <int, int> m;    //creating a map m
	int count = 0;	

	for (int i = 0; i < n; ++i)
	{
		m[arr[i]]++;               //for all elements in array incrementing value 
	}

	for (int i = 0; i < n; ++i)
	{
		count = count + m[X - arr[i]];   //Incrementing count by 1, if the element is their in #include <array>
		if(X - arr[i]== arr[i])
		{
			count--;
		}
	}

	return count/2;		
}




int main()
{
	int arr[] = {1, 5, 7, -4, 2};
	int X = 3;
	int n = sizeof(arr)/sizeof(arr[0]);
	int ans = numPairs(arr,X,n);
	cout<<"The number of pairs in the array with sum "<<X<<" is "<<ans;
	return 0;
}
Try It


C++ Online Test - Check Your Rank across the World


Next > < Prev
Scroll to Top