Find Pair of Elements in an Array whose Sum is Equal to a given number

Find Pair of Elements in an Array whose Sum is Equal to given number.  Given an array of n integers and a number x, We have to write a code to find a pair of elements(a,b) in an array whose sum is equal to a given number x. 

This is another important question asked in a technical interview.

Find Pair of Elements in an Array whose Sum is Equal to a given number

Let’s discuss the different approaches for solving this problem.

Method 1 – Brute Force Approach

The easiest way to find pair of elements in an array is by using two for loops.In this approach, we take one number from an array and loop through the array to check if the sum of two number is equal to the input number.

The time complexity of this approach is O(n2).

It is the simplest approach to find pair of elements in an array. This approach can work both for sorted and unsorted arrays. The only disadvantage with this approach is their time complexity.

Subscribe Our Tutorials

Get Latest Updates on Facebook

Method 2 – Time complexity O(nlogn) :

Algorithm to Find Pair of Elements in an Array whose Sum is Equal to a given number

1. Take two indexes and initialize with the first and last index of an array. So that we can start from both the ends.

2. Run a loop and check the condition first < last.

The time complexity of this approach is O(nlogn). This method works only with sorted arrays. If the array is not sorted then sort it first in ascending order.

Method 3 – Time complexity O(n)

Let’s try to solve this problem in O(n). In this approach, we use HashMap to solve this problem.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.