Find a pair in an array with a sum equal to the target using sorting.

Problem statement

Given array nums of n numbers and another number target, determines whether or not there exist two elements in nums whose sum is exactly equal to target.

Problem statement taken from: https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/

Example 1:

Example 2:

Explanation

The problem can be solved in O(NlogN) time, without using extra space. The NlogN is the average time taken to sort an array.

Sorting and two pointers

Algorithm

C++ solution

Golang solution

Originally published at https://alkeshghorpade.me.

Software Engineer. Working Saeloun. My portfolio https://alkeshghorpade.me