tutorialcup@gmail.com

Pair Sum in Array Equal to Number

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

Find pair of elements from an array whose sum is equal to a given number X

ALGORITHM 1 

Time Complexity: O(NlogN)
Space Complexity: O(1)
Concept:

Let say there are numbers

-1 5 7 -8 12 16 -30 -4
And we need to find a pair whose sum is say 17

Then the efficient way is shown below

1. Arrange the numbers in ascending order (Sort it )


2. Run a loop this way :
  • Let say one person stand at start of array and the second person stand at end

  • They add up the numbers on which they are standing                        

                    => -30 +16 =14

  • If their number is equal to the given number X then they enjoy

  • Else if the sum is lesser than the given number they ask the first person standing at start of array to move one step towards the end because if he travels right the number increases and hence the sum.

  • Similarly if the sum is more the person at the end is asked to move towards start by one step

  • We repeat until the persons collide as after that the same pairs will be obtained.

  • If no such pair is found then both become sad.

Important thing is the Sort() function.We should use Merge or Heap sort as they take O(NLogN) time.Orelse we can use sort() STL function. with parameters "sort(arr,arr+size)"

EXPECTED

Input:   -3 ,-4 , 10 , 0 ,3 ,-2 ,15 , 3
Sum:  7
Answer:  -3 and 10

#include <bits/stdc++.h>
using namespace std;

int main()
{
	int arr[] = {-3,-4,10,0,3,-2,15,3};
	int size_of_array = sizeof(arr)/sizeof(arr[0]);
	
	//RequiredSum is number to which the pair should sum to
	
	int RequiredSum = 7;
	
	sort(arr,arr + size_of_array); //sort the array

	int startIndex = 0 ,  endIndex = size_of_array - 1 , sum =0; //variables pointing on their respective indices and sum to store sum of the pair

	while(startIndex <endIndex) //We require a pair so 2 elements and hence both elements should be of different indices
	{
		sum = arr[startIndex] + arr[endIndex];
		if( sum == RequiredSum)
		{
			cout << "The numbers are " << arr[startIndex] <<" and " << arr[endIndex] <<endl;
			return 0;
		}

		else if(sum < RequiredSum) //if sum is less then we need to increase the smaller one
			startIndex ++;
		else //if the sum if more we need to decrease the larger number
			endIndex --;
	}
	cout << "No such pair exists.";
	return 0;
}
Try It

ALGORITHM 2

Time Complexity - O(NlogN)
Space Complexity - O(N)
Concept:

Let say there are numbers

-1 5 7 -8 12 16 -30 -4

and we need to find a pair whose sum is say 23

This concept is based on the Mapping approach.

1. Create a map such that each element is added.
2. If there exists a pair that sums to X then both the elements are present in map.
3. So we loop through the array and do this

  • Find if the (X – present) element is present in map
  • If present then print the number.

**You can STL map data structure for this purpose.Or else you can create an array for indexing where index are the value of the array element itself.(But using array has a disadvantage that its size is required.)

EXPECTED

Input:   -3 ,-4 , 10 , 0 ,3 ,-2 ,15 , 3
Sum:  7
Answer:  -3 and 10

#include <bits/stdc++.h>
using namespace std;

map <int,int> m;
map<int,int>::iterator it;

int main()
{
	int arr[] = {-3,-4,10,0,3,-2,15,3};
	int size_of_array = sizeof(arr)/sizeof(arr[0]);
	
	//cout << "Enter the number to which the pair should sum to"<<endl;
	
       //Let Sum = 7
	int x = 7;

	//cin >> x; // the number to which the sum of pair of elements must be equal

	for (int i = 0; i < size_of_array;++i)
	{
		//Scan and add elements into the map
		it = m.find(arr[i]);
		
		if(it == m.end())
			m.insert(make_pair(arr[i],1)); //Add the element in the map and set the count to 1 that represents it is present
	}

	for (int i = 0; i < size_of_array;i++)
	{
			it = m.find((x - arr[i]));  //If we have two numbers say m and n that sums to x then 
		//if we have m and if we find n in the map then we got the numbers.

			if(it != m.end()) //If it exists then we got the pair
			{
				pair<int,int> p = *it; //Obtain the pair so as to reference the 2nd number
				cout << "The numbers are " << arr[i] <<" and " << p.first <<endl;
				return 0;
			}
	}
	
	cout << "No such pair exists.";
	return 0;
}
Try It




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


Next > < Prev
Scroll to Top