MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / threeNumberSum

Function threeNumberSum

arrays/three-num-sum.js:3–27  ·  view source on GitHub ↗
(array, targetSum)

Source from the content-addressed store, hash-verified

1// Time O(n^2) | space O(n) where n is the number of three sums
2
3function threeNumberSum(array, targetSum) {
4 array.sort((a, b) => a - b);
5 const result = [];
6
7 for (let i = 0; i < array.length - 1; i++) {
8 const firstNumber = array[i];
9 let leftPointer = i + 1;
10 let rightPointer = array.length - 1;
11
12 while (leftPointer < rightPointer) {
13 const leftNumber = array[leftPointer];
14 const rightNumber = array[rightPointer];
15 if (firstNumber + leftNumber + rightNumber === targetSum) {
16 result.push([firstNumber, leftNumber, rightNumber]);
17 leftPointer++;
18 rightPointer--;
19 } else if (firstNumber + leftNumber + rightNumber < targetSum) {
20 leftPointer++;
21 } else {
22 rightPointer--;
23 }
24 }
25 }
26 return result;
27}
28
29const array = [12, 3, 1, 2, -6, 5, 0, -8, -1, 6];
30const targetSum = 0;

Callers

nothing calls this directly

Calls 1

pushMethod · 0.45

Tested by

no test coverage detected