Search This Blog

2024/04/05

Javascript Interview Question:Pairwise (FreeCodeCamp)

Problem Statement:
Given an array arr, find element pairs whose sum equal the second argument
arg and return the sum of their indices.

You may use multiple pairs that have the same numeric elements but
different indices. Each pair should use the lowest possible available
indices. Once an element has been used it cannot be reused to pair with
another element. For instance, pairwise([1, 1, 2], 3) creates a
pair [2, 1] using the 1 at index 0 rather than the 1 at index 1, because
0+2 < 1+2.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that
sum to 20 are [7, 13] and [9, 11]. We can then write out the array with
their indices and values.

Index 0 1 2 3 4
Value 7 9 11 13 15
Below we'll take their corresponding indices and add them.

7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Return 6

Test Case:
1) pairwise([1, 4, 2, 3, 0, 5], 7) should return 11.
2) Passed:pairwise([1, 3, 2, 4], 4) should return 1.
3) Passed:pairwise([1, 1, 1], 2) should return 1.
4) Passed:pairwise([0, 0, 0, 0, 1, 1], 1) should return 10.
5) Passed:pairwise([], 100) should return 0.

Solution:
function pairwise(myArr, sum) {
var newArray = [];
for (let i = 0; i < myArr.length; i++) {
newArray.push({ element: myArr[i], utilized: false });
}

var middleOfSolution=[];
for (let j = 0; j < myArr.length - 1; j++) {
for (let k = j + 1; k < myArr.length; k++) {
if(newArray[j].utilized == false && newArray[k].utilized == false)
{
if(myArr[j] + myArr[k] == sum){
middleOfSolution.push({"sum":sum,"first":myArr[j]
,"second":myArr[k],"firstIndex":j,"secondIndex":k})

newArray[k].utilized = true;
newArray[j].utilized = true
}
}

}
}
let result = middleOfSolution.reduce((acc,element)=>{
acc = acc + element.firstIndex + element.secondIndex
return acc
},0)

return result;
}

let mySum = pairwise([7, 9, 11, 13, 15], 20);
console.log(mySum)

Output:
6

No comments:

Post a Comment