Skip to content

Instantly share code, notes, and snippets.

@omokehinde
Last active February 1, 2022 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omokehinde/cc0000040a023639a483a769da626d49 to your computer and use it in GitHub Desktop.
Save omokehinde/cc0000040a023639a483a769da626d49 to your computer and use it in GitHub Desktop.
HackerRank Beautiful Triplets challenge
# Given a sequence of integers , a triplet is beautiful if:
# Given an increasing sequenc of integers and the value of , count the number of beautiful triplets in the sequence.
# Example
# There are three beautiful triplets, by index: . To test the first triplet, and .
# Function Description
# Complete the beautifulTriplets function in the editor below.
# beautifulTriplets has the following parameters:
# int d: the value to match
# int arr[n]: the sequence, sorted ascending
# Returns
# int: the number of beautiful triplets
# 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 .
# Constraints
# Sample Input
# STDIN Function
# ----- --------
# 7 3 arr[] size n = 7, d = 3
# 1 2 4 5 7 8 10 arr = [1, 2, 4, 5, 7, 8, 10]
# Sample Output
# 3
# Explanation
# 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 .
# Language
# Python 3
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'beautifulTriplets' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER d
# 2. INTEGER_ARRAY arr
#
def beautifulTriplets(d, arr):
# Write your code here
triplets = 0
for i in arr:
if i+d in arr and i+d*2 in arr:
triplets += 1
return triplets
@omokehinde
Copy link
Author

I found a way to get the triplet by checking if the sum of an element i+d and i+2*d is in the array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment