Program to check number of triplets from an array whose sum is less than target or not Python


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 −

Example

 Live Demo

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))

Input

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

Output

5

Updated on: 21-Oct-2020

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements