I recently participated in a technical interview for a software development company. The question presented to me was as follows:
Given an array of numbers (n), find two numbers that sum up to a target number (k) and display them.
Example:
Input: n = [2,6,4,5,7,1], k = 8
Output: result=(2,6),(7,1)
Here is the solution I provided:
function findSum(n,k){
let aux = []
for (let i = 0; i < n.length; i++) {
for (let j = i+1; j < n.length; j++) {
if (n[i] + n[j] == k) {
aux.push({ first: n[i], second: n[j] })
}
}
}
return aux;
}
After presenting my solution, they mentioned that it might be possible to solve the problem using some sort of key or mapping. Does anyone know how to achieve this with only one loop?