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

Function threeSum

arrays/three-num-sum.js:40–74  ·  view source on GitHub ↗
(nums)

Source from the content-addressed store, hash-verified

38// Time O(n^2)
39// Space O(n)
40var threeSum = function (nums) {
41 nums.sort((a, b) => a - b);
42 let triplets = [];
43
44 for (let i = 0; i < nums.length - 2; i++) {
45 if (i > 0 && nums[i] == nums[i - 1]) continue; //avoid duplicates
46
47 let leftPointer = i + 1;
48 let rightPointer = nums.length - 1;
49
50 while (leftPointer < rightPointer) {
51 let currentSum = nums[i] + nums[leftPointer] + nums[rightPointer];
52 if (currentSum === 0) {
53 triplets.push([nums[i], nums[leftPointer], nums[rightPointer]]);
54 leftPointer++;
55 rightPointer--;
56 while (
57 leftPointer < rightPointer &&
58 nums[leftPointer] == nums[leftPointer - 1]
59 )
60 leftPointer++; //avoid duplicates
61 while (
62 leftPointer < rightPointer &&
63 nums[rightPointer] == nums[rightPointer + 1]
64 )
65 rightPointer--; //avoid duplicates
66 } else if (currentSum > 0) {
67 rightPointer--;
68 } else if (currentSum < 0) {
69 leftPointer++;
70 }
71 }
72 }
73 return triplets;
74};

Callers

nothing calls this directly

Calls 1

pushMethod · 0.45

Tested by

no test coverage detected