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

Building AWS data pipeline for Morale Check and Attrition Predictor

How To Use AWS EC2, EBS And S3 With The Help Of AWS CLI (Command Line Interface)

Building real conversations with Dialogflow and App.Chatbot

robot made of parts from constructor for children

User Management with Okta SDK and Spring Boot

Reduce Lag on Multiplayer games in Unity&Photon Pun2

6 Steps to Crack the System Design Interview

Let’s debunk the main myths about learning how to code

iOS Vs Android: Which is Best for Your App Development?

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

Use of python dictionary get function

Hackerrank — Insert Node in linked list walkthrough #Python #Hackerrank

CaDS— Code and Data Society

[LeetCode]#2042. Check if Numbers Are Ascending in a Sentence