Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Javascript Program to Find a triplet that sum to a given value
Next article icon

Javascript Program to Count triplets with sum smaller than a given value

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of distinct integers and a sum value. Find the count of triplets with a sum smaller than the given sum value. The expected Time Complexity is O(n2).

Examples: 

Input : arr[] = {-2, 0, 1, 3}         sum = 2. Output : 2 Explanation :  Below are triplets with sum less than 2                (-2, 0, 1) and (-2, 0, 3)   Input : arr[] = {5, 1, 3, 4, 7}         sum = 12. Output : 4 Explanation :  Below are triplets with sum less than 12                (1, 3, 4), (1, 3, 5), (1, 3, 7) and                 (1, 4, 5)

Native Approach:

A Native Solution is to run three loops to consider all triplets individually. For every triplet, compare the sums and increment count if the triplet sum is smaller than the given sum. 

Example:

JavaScript
// A Simple Javascript program to count triplets with sum smaller // than a given value let arr = [5, 1, 3, 4, 7];  function countTriplets(n, sum) {      // Initialize result     let ans = 0;      // Fix the first element as A[i]     for (let i = 0; i < n - 2; i++) {         // Fix the second element as A[j]         for (let j = i + 1; j < n - 1; j++) {             // Now look for the third number             for (let k = j + 1; k < n; k++)                 if (arr[i] + arr[j] + arr[k] < sum)                     ans++;         }     }     return ans; }  // Driver method to test the above function let sum = 12; console.log(countTriplets(arr.length, sum)); 

Output
4 

Complexity Analysis:

  • Time Complexity: O(n3)
  • Auxiliary Space: O(1)

Efficient Solution:

Efficient Solution can count triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop.

1) Sort the input array in increasing order. 2) Initialize result as 0. 3) Run a loop from i = 0 to n-2.  An iteration of this loop finds all    triplets with arr[i] as first element.      a) Initialize other two elements as corner elements of subarray         arr[i+1..n-1], i.e., j = i+1 and k = n-1      b) Move j and k toward each other until they meet, i.e., while (j= sum                 then k--             // Else for current i and j, there can (k-j) possible third elements             // that satisfy the constraint.             (ii) Else Do ans += (k - j) followed by j++ 

Below is the implementation of the above idea. 

JavaScript
// A Simple Javascript program to count triplets with sum smaller // than a given value let arr = [5, 1, 3, 4, 7];  function countTriplets(n, sum) {      // Sort input array     arr.sort(function (a, b) { return b - a });      // Initialize result     let ans = 0;      // Every iteration of loop counts triplet with     // first element as arr[i].     for (let i = 0; i < n - 2; i++) {          // Initialize other two elements as corner elements         // of subarray arr[j+1..k]         let j = i + 1, k = n - 1;          // Use Meet in the Middle concept         while (j < k) {             // If sum of current triplet is more or equal,             // move right corner to look for smaller values             if (arr[i] + arr[j] + arr[k] >= sum)                 k--;              // Else move left corner             else {                  // This is important. For current i and j, there                 // can be total k-j third elements.                 ans += (k - j);                 j++;             }         }     }     return ans; }  // Driver method to test the above function let sum = 12; console.log(countTriplets(arr.length, sum)); 

Output
4 

Complexity Analysis:

  • Time Complexity: O(n2)
  • Auxiliary Space: O(1)

Please refer complete article on Count triplets with sum smaller than a given value for more details!


Next Article
Javascript Program to Find a triplet that sum to a given value
author
kartik
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • DSA
  • Arrays
  • Amazon
  • SAP Labs
Practice Tags :
  • Amazon
  • SAP Labs
  • Arrays

Similar Reads

  • Count triplets with sum smaller than a given value
    Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input :
    11 min read
  • Javascript Program to Find a triplet that sum to a given value
    Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. Examples: Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There i
    6 min read
  • Javascript Program to Find all triplets with zero sum
    Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples : Input : arr[] = {0, -1, 2, -3, 1}Output : (0 -1 1), (2 -3 1)Explanation : The triplets with zero sum are0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5}Output : 1 -2 1Explan
    6 min read
  • Find all triplets that sum to a given value or less
    Given an array, arr[] and integer X. Find all the possible triplets from an arr[] whose sum is either equal to less than X. Example: Input : arr[] = {-1, 1, 3, 2}, X = 3Output: (-1, 1, 3), (-1, 1, 2)Explanation: If checked manually, the above two are the only triplets from possible 4 triplets whose
    7 min read
  • Javascript Program to Find a triplet such that sum of two equals to third element
    Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element. Examples: Input: {5, 32, 1, 7, 10, 50, 19, 21, 2}Output: 21, 2, 19Input: {5, 32, 1, 7, 10, 50, 19, 21, 0}Output: no such triplet existQuestion source: Arcesium Interview Experience
    3 min read
  • 3 Sum - Count Triplets With Given Sum In Sorted Array
    Given a sorted array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. More specifically, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k. Exam
    10 min read
  • Length of Smallest subarray in range 1 to N with sum greater than a given value
    Given two numbers N and S, the task is to find the length of smallest subarray in range (1, N) such that the sum of those chosen numbers is greater than S. Examples: Input: N = 5, S = 11 Output: 3 Explanation: Smallest subarray with sum > 11 = {5, 4, 3} Input: N = 4, S = 7 Output: 3 Explanation:
    9 min read
  • 3 Sum - Count all triplets with given sum
    Given an array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: 2Explanation: Two triplets that add up to -2 are:arr[0] + arr[3] + arr[4] = 0 + (-3) + (1
    10 min read
  • JavaScript Program to Count the Number of Possible Triangles in Array
    Triangles are basic geometric figures with three sides and three angles. Finding the number of triangles that can be created from a given set of side lengths is a frequent challenge in computational programming. In this article, we'll see how to use a JavaScript array to calculate the total number o
    4 min read
  • Javascript Program to Count Inversions of size three in a given array
    Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3. Example : Input: {8, 4, 2, 1}Output: 4The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).Input: {
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences