Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript program to count triplets with sum smaller than a given value
In this article, we will learn to count triplets with a sum smaller than a given value in JavaScript. Triplets in an array whose sum is less than a provided number is a popular problem in competitive coding and algorithm design.
Problem Statement
Given an array of integers and a target sum, we need to find the number of triplets (a, b, c) where the sum of three elements is less than the given value.
Input:
const arr = [5, 1, 3, 4, 7]; const sum = 12;
Output:
4
Explanation: The valid triplets are:
- (1, 3, 4) ? sum = 8
- (1, 3, 5) ? sum = 9
- (1, 3, 7) ? sum = 11
- (1, 4, 5) ? sum = 10
All these triplets have sums less than 12.
Using Sorting and Two-Pointer Technique
This problem can be solved efficiently by sorting the array and employing the two-pointer technique. First, we sort the array in ascending order, then for each element, we use two pointers to find valid triplets whose sum is less than the target value.
Algorithm Steps
- Sort the array in ascending order
- Fix the first element and use two pointers for the remaining elements
- Initialize left pointer after current element and right pointer at the end
- Calculate sum of current triplet:
arr[i] + arr[left] + arr[right] - If sum ? target, decrement right pointer
- If sum
Implementation
function countTriplets(arr, sum) {
let count = 0;
// Sort the array in ascending order
arr.sort((a, b) => a - b);
// Fix first element and find pairs for remaining
for (let i = 0; i < arr.length - 2; i++) {
let left = i + 1;
let right = arr.length - 1;
while (left < right) {
let currentSum = arr[i] + arr[left] + arr[right];
if (currentSum >= sum) {
// Sum is too large, decrease right pointer
right--;
} else {
// All triplets between left and right are valid
count += right - left;
left++;
}
}
}
return count;
}
// Test the function
const arr = [5, 1, 3, 4, 7];
const targetSum = 12;
const result = countTriplets(arr, targetSum);
console.log(`Array: [${arr.join(', ')}]`);
console.log(`Target sum: ${targetSum}`);
console.log(`Number of triplets with sum < ${targetSum}: ${result}`);
Array: [5, 1, 3, 4, 7] Target sum: 12 Number of triplets with sum < 12: 4
How It Works
Let's trace through the algorithm with our example:
- After sorting: [1, 3, 4, 5, 7]
-
i = 0 (arr[0] = 1): left = 1, right = 4
- Sum = 1 + 3 + 7 = 11
- Sum = 1 + 4 + 7 = 12 ? 12 ? right--
- Sum = 1 + 4 + 5 = 10
- i = 1 (arr[1] = 3): All remaining sums ? 12
- Total count: 4
Example with Different Input
function demonstrateWithDifferentInput() {
const testCases = [
{ arr: [1, 2, 3, 4], sum: 6 },
{ arr: [2, 7, 9, 3, 1], sum: 10 },
{ arr: [1, 1, 1, 1], sum: 4 }
];
testCases.forEach((test, index) => {
const result = countTriplets([...test.arr], test.sum);
console.log(`Test ${index + 1}: [${test.arr}], sum < ${test.sum} ? ${result} triplets`);
});
}
demonstrateWithDifferentInput();
Test 1: [1,2,3,4], sum < 6 ? 1 triplets Test 2: [2,7,9,3,1], sum < 10 ? 2 triplets Test 3: [1,1,1,1], sum < 4 ? 4 triplets
Complexity Analysis
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(n²) | O(n log n) for sorting + O(n²) for two-pointer traversal |
| Space | O(1) | Only uses constant extra space for pointers and counter |
Key Points
- Sorting is crucial for the two-pointer technique to work correctly
- When sum
- This approach is much more efficient than the brute force O(n³) solution
- The algorithm handles duplicate values correctly
Conclusion
The sorting and two-pointer approach efficiently solves the triplet counting problem in O(n²) time. This technique significantly outperforms brute force methods and is essential for handling large datasets in competitive programming scenarios.
