Javatpoint Logo
Javatpoint Logo

Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)

Create a programme that checks whether there are two entries in the array A[] whose total is exactly x given an array A[] of n numbers and another number x.




Pair with a given sum -2 is (-3, 1)
 Valid pair exists

If we add the outputs, 1 + (-3) = -2 will result.



No valid pair exists for 0

Method: Using simple logic by calculating the array's elements themselves.


Check for pairs in array A[] with sum as x in C++ given an array A[] and a number x.


Pair with a given sum -2 is (-3, 1)
Valid pair exists

Time Complexity: O(n2)

Auxiliary Space: O(1)

Method 1: Sorting and Two-Pointers technique.

Using the two-pointer method to tackle this problem can be challenging. However, the array needs to be sorted before utilising the two pointer strategy. The two pointers that mark the beginning and end of the array can be taken once the array has been sorted. Shift the left pointer to increase the value of the necessary sum if the sum is less than the needed value and the right pointer to reduce it if the sum is more than the sum of the two elements. Let's use an example to better grasp this.

Give the array 1, 4, 45, 6, 10, -8, and the sum to be determined as 16.

Array is sorted after that
A = {-8, 1, 4, 6, 10, 45}

Now, increase "l" when the pair's sum is less than the necessary sum and decrease "r" when the pair's sum is more than the necessary amount.
This is due to the fact that travelling from left to right (while also sorting the array) in order to find the number that might enhance the total of a pair when the sum is smaller than the needed sum results in "l++" and vice versa.

Start with l = 0 and r = 5.
   • A[l] + A[r] (-8 + 45) > 16 resulting in r reduction Now r = 4
   • A[l] + A[r] (-8 + 10) add l. I is now equal to 1.
   • A[l] + A[r] (1 + 10) add l. At this point, l equals 2.
   • A[l] + A[r] (4 + 10) raise l, making l equal to 3.
   • A[l] + A[r] (6 + 10) == 16 => selected candidates (return 1)

Note: This algorithm only reports one pair if there are multiple pairs with the provided amount. nonetheless, readily adapted for this.


  • hasArrayTwoCandidates (A[], ar_size, sum)
  • Sort the array in non-decreasing order.
  • Initialize two index variables to find the candidate elements in the sorted array.
    • Initialize first to the leftmost index: l = 0
    • Initialize second the rightmost index: r = ar_size-1
  • Loop while l < r.
    • If (A[l] + A[r] == sum) then return 1
    • Else if( A[l] + A[r] < sum ) then l++
    • Else r-
  • No candidates in the whole array - return 0

The application of the aforementioned strategy is seen below:



Array has two elements with given sum

Complexity Analysis:

Time Complexity: Depends on what sorting algorithm we use.

If Merge Sort or Heap Sort is used then (-)(nlogn) in the worst case.

If Quick Sort is used then O(n^2) in the worst case.

Auxiliary Space: This too depends on sorting algorithm. The auxiliary space is O(n) for merge sort and O(1) for Heap Sort.

Method 2: Hashing

Approach: By employing the hashing method, this issue can be effectively resolved. Use a hash map to see whether there is a value target sum-x that can be added to the current array value x(let) to produce target sum. Continuous time can be used to do this. Let's examine the next illustration.

arr[] = {0, -1, 2, -3, 1}

total = -2

Now begin your traverse:
   • '-2' is not an acceptable number for '0,' thus store '0' in the hash map in step 1.
   • Since "-1" is not a valid number, "-1" should be stored in the hash map.
   • Store "2" in hash map because the integer "-4" is not a valid value for "2".
   • Since there is no acceptable number "1" for "-3," store "-3" in hash map.
   • The answer is 1, -3 because "1" is a valid number.


  • Initialize an empty hash table s.
  • Do following for each element A[i] in A[]
    • If s[x - A[i]] is set then print the pair (A[i], x - A[i])
    • Insert A[i] into s.




Pair with given sum 16 is (10,6)

Complexity Analysis:

Time Complexity: O(n).

As the whole array is needed to be traversed only once.

Auxiliary Space: O(n).

A hash map has been used to store array elements.

If the pair is made up of numbers that appear twice in the array, for example: array = [3,4,3]; pair = (3,3); target sum = 6, the answer will still be valid.

Method 3: Using remainders of the elements less than x.

The goal is to add up all the elements that leave behind remainders when multiplied by x, from 0 to x-1. If x is 6, then the sum of the numbers that are less than 6 and have remainders that add up to 6 is 6. For instance, the array contains the entries 2, 4, and the remainders 2%6 = 2 and 4%6 = 4, which together equal 6. In a similar manner, we must search for pairs with the remainders (1,5),(2,4). (3,3). If we have at least one element with a residual of 1 and at least one element with a remainder of 5, we will undoubtedly obtain a sum of 6. Since the elements for the resulting pair should be less than 6, we do not take (0,6) into consideration here. In the case of (3,3), we must first determine if there are any elements with a remainder of 3, after which we can state that "There exists a pair whose total equals x."


  • Create an array with size x.
  • Initialize all rem elements to zero.
  • Traverse the given array
    • Do the following if arr[i] is less than x:
      • r=arr[i]%x which is done to get the remainder.
      • rem[r]=rem[r]+1 i.e. increasing the count of elements that have remainder r when divided with x.
  • Now, traverse the rem array from 1 to x/2.
    • If(rem[i]> 0 and rem[x-i]>0) then print "YES" and come out of the loop. This means that we have a pair that results in x upon doing.
  • Now when we reach at x/2 in the above loop
    • If x is even, for getting a pair we should have two elements with remainder x/2.
      • If rem[x/2]>1 then print "YES" else print "NO"
    • If it is not satisfied that is x is odd, it will have a separate pair with x-x/2.
      • If rem[x/2]>1 and rem[x-x/2]>1 , then print "Yes" else, print"No";




Complexity Analysis:

Time Complexity: O(n+x).

Auxiliary Space: O(x).

An unordered map can also determine the indices of a pair that add up to a specified amount. The only modification required in this case is the addition of storing element indices as values alongside each element's key.



1 2

Time Complexity: O(n)

Auxiliary Space: O(n)

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA