-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay32.js
More file actions
49 lines (34 loc) · 1.28 KB
/
Day32.js
File metadata and controls
49 lines (34 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Sure! Here's a JavaScript coding question you might encounter in an interview:
// Question:
// Given an array of integers, write a function findPairs that takes two arguments: the array of integers and a target sum. The function should find all pairs of integers in the array that sum up to the target sum and return them as an array of arrays.
function findPairs(arr, targetSum) {
const pairs = [];
const seen = new Set();
for (let num of arr) {
const complement = targetSum - num;
if (seen.has(complement)) {
pairs.push([num, complement]);
}
seen.add(num);
}
return pairs;
}
// Test the function
const arr = [3, 1, 5, 8, 2, 6];
const targetSum = 9;
console.log(findPairs(arr, targetSum)); // Output: [[3, 6], [1, 8], [5, 4]]
// function findPairs(arr, targetSum) {
// const pairs = [];
// for (let i = 0; i < arr.length - 1; i++) {
// for (let j = i + 1; j < arr.length; j++) {
// if (arr[i] + arr[j] === targetSum) {
// pairs.push([arr[i], arr[j]]);
// }
// }
// }
// return pairs;
// }
// // Test the function
// const arr = [3, 1, 5, 8, 2, 6];
// const targetSum = 9;
// console.log(findPairs(arr, targetSum)); // Output: [[3, 6], [1, 8], [5, 4]]