Find two numbers in an array whose sum is equal to k.

Find two numbers in an array whose sum is equal to k.

There are multiple way to solve this problem

1. Find the elements using a brute force approach. Which is a costlier operation(O(n2).
2. We can sort the list and search for the values in a linear way. But still it would also cost O(nlogn).
3. The most efficient way of doing this is using hash map.

function findElement (array, result) {
var hash = new Object();
for (let [loop, val] of array.entries()) {
if (typeof hash[result - val] !== "undefined") {
console.log( loop, hash[result - val]);
}
if (!hash.val) {
hash[val] = loop;
}
}
}
findElement([10, 123, 0, 4, 5, 5], 10);


Reference: http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0101-74382015000200423

No comments:

Post a Comment

Featured Post

IRCTC 120 days ticket date calculator.

IRCTC Ticket Date App IRCTC 120 days advance ticket date calculator.