- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called nums and another value target, we have to find the number of triples (i < j < k) that exist such that nums[i] + nums[j] + nums[k] < target.

So, if the input is like nums = [−2, 6, 4, 3, 8], target = 12, then the output will be 5, as the triplets are: [−2,6,4], [−2,6,3], [−2,4,3], [−2,4,8], [−2,3,8]

To solve this, we will follow these steps −

sort the list nums

ans := 0

n := size of nums

for i in range 0 to n−1, do

k := n − 1

for j in range i + 1 to n−1, do

while k > j and nums[i] + nums[k] + nums[j] >= target, do

k := k − 1

if j is same as k, then

ans := ans + k − j

return ans

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums, target): nums.sort() ans = 0 n = len(nums) for i in range(n): k = n − 1 for j in range(i + 1, n): while k > j and nums[i] + nums[k] + nums[j] >= target: k -= 1 if j == k: break ans += k − j return ans ob1 = Solution() nums = [−2, 6, 4, 3, 8] target = 12 print(ob1.solve(nums, target))

[-2, 6, 4, 3, 8], 12

5

- Related Questions & Answers
- Print triplets with sum less than or equal to k in C Program
- Program to find number of sublists whose sum is given target in python
- Program to find sum of two numbers which are less than the target in Python
- Program to find number of unique four indices where they can generate sum less than target from four lists in python
- Count pairs in a sorted array whose sum is less than x in C++
- Program to count maximum number of distinct pairs whose differences are larger than target in Python
- C Program to check if an Array is Palindrome or not
- Program to check a number is ugly number or not in Python
- Program to check we can find four elements whose sum is same as k or not in Python
- Program to check robot can reach target position or not in Python
- Python program to check if a number is Prime or not
- Python program to check a number n is weird or not
- Python program to check credit card number is valid or not
- Program to find number of K-Length sublists whose average is greater or same as target in python
- Program to check a number is power of two or not in Python

Advertisements