-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0259-3sum-smaller.js
More file actions
29 lines (24 loc) · 857 Bytes
/
0259-3sum-smaller.js
File metadata and controls
29 lines (24 loc) · 857 Bytes
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
/**
* 3sum Smaller
* Time Complexity: O(N^2)
* Space Complexity: O(log N)
*/
var threeSumSmaller = function (nums, target) {
nums.sort((alpha, beta) => alpha - beta);
const arrayLength = nums.length;
let totalTripletsCount = 0;
for (let firstElementIndex = 0; firstElementIndex < arrayLength - 2; firstElementIndex++) {
let leftBoundary = firstElementIndex + 1;
let rightBoundary = arrayLength - 1;
while (leftBoundary < rightBoundary) {
const currentSumOfThree = nums[firstElementIndex] + nums[leftBoundary] + nums[rightBoundary];
if (currentSumOfThree < target) {
totalTripletsCount += (rightBoundary - leftBoundary);
leftBoundary++;
} else {
rightBoundary--;
}
}
}
return totalTripletsCount;
};