Two Pair Sum
Contents
#pairs
Given an array containing N integers and an number S denoting a target Sum.
Find two distinct integers that can pair up to form target sum. Let us assume there will be only one such pair.
Input:
array = [10, 5, 2, 3, -6, 9, 11 ]
S = 4
output:
[10, -6]
Solution:
Naive Approach:
We can use two loops which will compare each element with other elements that gives the sum. This will take an order of O(n^2).
Optimal Approach O(N) :
In this approach we will avoid one loop, instead of comparing the second value with a loop, we will use a map to lookup the subtracted value from the total sum. Map will take only a constant time to lookup the value. So the total running time of this approach will be order of O(N).
|
|