THE PROBLEM STATEMENT
You have an integer array and a sum. You have to find first pair that sums up to the given sum number.
Return the pair.
Example 1
Input: Array = [10,2,1,2,3,7], Sum = 4Output: [2, 2]
Example 2
Input: Array = [3,2,1,4,1,4], Sum = 5Output: [3, 2]
Example 3
Input: Array = [1, 2, 3, 7, 10], Sum = 14Output: null
SOLUTION?
So before you see my solution below I recommend you to try solving it yourself first.
SOLUTION
function findPair(arr, sum) {
if (arr == null || arr.length < 2) throw new Exception("Array should have more than one elements.");
var datatable = {};
// store numbers in an object
for (var i = 0; i < arr.length; i++) {
// number should not be less than 1
if (arr[i] < 1) throw new Exception("Array should contain numbers greater than 0.");
// value keeps track of occourance of the number in array
if (datatable[arr[i]]) {
datatable[arr[i]]++;
} else {
datatable[arr[i]] = 1;
}
}
for (var i = 0; i < arr.length; i++) {
if (sum - arr[i] == arr[i]) {
if (datatable[arr[i]] > 1)
return [arr[i], arr[i]];
} else {
if (datatable[sum - arr[i]])
return [arr[i], sum - arr[i]];
}
}
return null;
}
console.log(findPair([6, 4], 10));
// [ 6, 4 ]
console.log(findPair([6, 4, 2, 1, 1000, 2], 12));
// null
console.log(findPair([6, 4, 2, 1, 1000, 2], 6));
// [ 4, 2 ]
console.log(findPair([6, 4, 2, 1, 1000, 2], 1002));
// [ 2, 1000 ]
console.log(findPair([3, 4, 4, 8, 6, 2], 8));
// [ 4, 4 ]This solution have complexity of n so the Big O notation is O(n)
Now what if we want indexes of the numbers in array that sum up to be the given sum number.
Example 1
Input: Array = [10,2,1,2,3,7], Sum = 4Output: [1, 3]
Example 2
Input: Array = [3,2,1,4,1,4], Sum = 5Output: [0, 1]
Following is the method that returns indexes.
function findPairIndexes(arr, sum) {
if (arr == null || arr.length < 2) throw new Exception("Array should have more than one elements.");
for (var i = 0; i < arr.length; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] < 1 || arr[j] < 1) throw new Exception("Array should contain numbers greater than 0.");
if (arr[i] + arr[j] == sum) {
return [i, j];
}
}
}
return null;
}
console.log(findPairIndexes([6, 4], 10));
// [ 0, 1 ]
console.log(findPairIndexes([6, 4, 2, 1, 1000, 2], 12));
// null
console.log(findPairIndexes([6, 4, 2, 1, 1000, 2], 6));
// [ 1, 2 ]
console.log(findPairIndexes([6, 4, 2, 1, 1000, 2], 1002));
// [ 2, 4 ]
console.log(findPairIndexes([3, 4, 4, 8, 6, 2], 8));
// [ 1, 2 ]This solution have complexity of n square so the Big O notation is O(n2)
Thank you for stopping by. Don’t forget to comment. Happy coding!
