Beautiful Triplets

Parag Naik
2 min readApr 20, 2021

--

Problem statement:-

Problem statement with example

Solution:-
A very straight forward hackerrank problem where we have to find the count of triplet form based on condition given in the problem statement.

Photo by rahmani KRESNA on Unsplash

In one of the approach we could use 3 for loops but it will create problem for huge array and thus hamper the execution time and degrade the time complexity. Let’s move towards the code.

def beautifulTriplets(d, arr):
count=0
for i in range(len(arr)):
j=arr[i]+d
if j in arr and j+d in arr:
count+=1
return count

We will first declare a variable which will count the number of triplets say count and initialize it to 0.The we will iterate each element in the list and add “d” to it and store it in “j” and check if the sum is present in the list if so the first condition i.e arr[i]-arr[j]=d and then we will d to j to check for condition arr[k]-arr[j]=d.If both the conditions are staified we will increment count by one and at the end of the iteration we will return the value of count.

Conclusion:-
Life is about how much you can take and keep fighting, how much you can suffer and keep moving forward.”
Currently I am in a lockdown and each day is very tough for me.Things are not working for me,feels like I am stuck .This is the best quote I could hang on to it.Keep learning and keep hustling…(cheers:-PN)

--

--

Parag Naik
Parag Naik

No responses yet