Program to find number of good triplets in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums, and three different integers a, b and c. We have to find the number of good triplets. A triplet (nums[i], nums[j], nums[k]) is said to be a good triplet if the following conditions are true −

  • 0 <= i < j < k < number of elements in nums

  • |nums[i] - nums[j]| <= a

  • |nums[j] - nums[k]| <= b

  • |nums[i] - nums[k]| <= c

We have to count the number of good triplets.

So, if the input is like nums= [5,2,3,3,12,9], a = 7, b = 2, c = 3, then the output will be 4 because the good triplets are [(5,2,3), (5,2,3), (5,3,3), (2,3,3)]

To solve this, we will follow these steps −

  • res := 0

  • for i in range 0 to size of nums - 1, do

    • for j in range i+1 to size of nums - 1, do

      • for k in range j+1 to size of nums - 1, do

        • if |nums[i] - nums[j]| <= a and |nums[j] - nums[k]| <= b and |nums[i] - nums[k]| <= c, then

          • res := res + 1

  • return res

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums, a, b, c):
   res = 0
   for i in range(len(nums)):
      for j in range(i+1, len(nums)):
         for k in range(j+1, len(nums)):
            if abs(nums[i] - nums[j]) <= a and abs(nums[j] - nums[k]) <= b and abs(nums[i] - nums[k]) <= c:
               res += 1
   return res

nums= [5,2,3,3,12,9]
a = 7
b = 2
c = 3
print(solve(nums, a, b, c))

Input

[5,2,3,3,12,9], 7, 2 3

Output

4
raja
Published on 17-May-2021 12:26:06
Advertisements