Hackerrank - Beautiful Triplets Solution
1 min read

Hackerrank - Beautiful Triplets Solution

Hackerrank - Beautiful Triplets Solution

Given a sequence of integers , a triplet  is beautiful if:

Given an increasing sequence of integers and the value of , count the number of beautiful triplets in the sequence.

For example, the sequence  and . There are three beautiful triplets, by index: . To test the first triplet,  and .

Function Description

Complete the beautifulTriplets function in the editor below. It must return an integer that represents the number of beautiful triplets in the sequence.

beautifulTriplets has the following parameters:

  • d: an integer
  • arr: an array of integers, sorted ascending

Input Format

The first line contains  space-separated integers  and , the length of the sequence and the beautiful difference.
The second line contains  space-separated integers .


Output Format

Print a single line denoting the number of beautiful triplets in the sequence.

Sample Input

7 3
1 2 4 5 7 8 10

Sample Output



The input sequence is , and our beautiful difference . There are many possible triplets , but our only beautiful triplets are  ,  and  by value not index. Please see the equations below:

Recall that a beautiful triplet satisfies the following equivalence relation:  where .

Solution in Python

def beautifulTriplets(d, arr):
    a = set(arr)
    return len([1 for i in arr if i+d in a and i+d*2 in a])
n,d = map(int,input().split())
arr = list(map(int,input().split()))
print(beautifulTriplets(d, arr))

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.