Count Triplets — Day 28(Python)

Triplets(Pinterest)

Count triplets with a sum smaller than a given value.

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)
class TripletCounter:
def countTriplets(self, arr, n, sum):
counter = 0
for a in range(len(arr)-2):
for b in range(a+1, len(arr)-1):
for c in range(b+1, len(arr)):
if arr[a] + arr[b] + arr[c] < sum:
counter += 1
return counter
Initializing the variables
class TripletCounter:
def countTriplets(self, arr, n, sum):
arr.sort()
counter = 0
for i in range(0,n-2):
j = i + 1
k = n-1
while(j < k):
if (arr[i]+arr[j]+arr[k] >=sum):
k = k-1
else:
ans += (k - j)
j = j+1
return ans

--

--

--

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

TryHackMe : Nmap Room

The way to govern your data assets optimally

How to create a Telegram bot, and send messages with Python

Serverless Application using riff

A Step-by-Step Guide to Finding the Right Custom Software Development Team

Plotting scatter ,line & bar combo using Py script Power BI in 2 minutes

How much am I worth?

Spiky.ai Engineering Teams Hiring Process Part 3: Technical Interview

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Annamariya Tharayil

Annamariya Tharayil

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

More from Medium

A Guide to Hosting a Database

Back to the radio app after a very long pause

An intermediate’s guide to Git Version Control — in terminal: branching and merging

Remove Nth Node From End of List — Day 107(Python)