HackerRank Beautiful Triplets Problem Solution
In this post, we will solve HackerRank Beautiful Triplets Problem Solution.
Given a sequence of integers a, a triplet (a[i], a[j], a[k]) is beautiful if:
- i<j<k
- a[j] = a[i] = a[k] – a[j] = d
Given an increasing sequenc of integers and the value of d. count the number of beautiful triplets in the sequence.
Example
arr = [2, 2, 3, 4, 5]
d = 1
There are three beautiful triplets, by index: [i, j, k] = [0, 2, 3], [1, 2, 3], [2, 3, 4]. To test the first triplet, arr[j] = arr[i] = 3-2 = 1 and arr[k] = arr[j] = 4-3 = 1.
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 2 space-separated integers, n and d, the length of the sequence and
the beautiful difference.
The second line contains n space-separated integers arr[i].
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 (arr[i], arr[j], arr[k]), but our only beautiful triplets are
(1,4,7), (4, 7, 10) and (2, 5, 8) by value, not index. Please see the equations below:
7-4 4-1=3=d 10-77-4=3=d 8 5 5 23 d
Recall that a beautiful triplet satisfies the following equivalence relation:
arr[j] = arr[i] = arr[k] – arr[j] = d where i < j < k.
Beautiful Triplets C Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, d, i, j, k, nb = 0;
int *arr;
scanf("%d %d", &n, &d);
arr = malloc(n * sizeof(int));
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for(j = 1; j < n - 1; j++) {
for(i = 0; i < j; i++) {
if(arr[j] - arr[i] == d) {
for(k = j + 1; k < n; k++) {
if(arr[k] - arr[j] == d) {
nb++;
}
}
}
}
}
printf("%d", nb);
return 0;
}
Beautiful Triplets C++ Solution
#include <bits/stdc++.h>
using namespace std;
#define REPU(i, a, b) for (int i = (a); i < (b); ++i)
#define REPD(i, a, b) for (int i = (a); i > (b); --i)
#define MEM(a, x) memset(a, x, sizeof(a))
#define ALL(a) a.begin(), a.end()
#define UNIQUE(a) a.erase(unique(ALL(a)), a.end())
typedef long long ll;
const int MOD = 1000000007;
template<class T> inline T tmin(T a, T b) { return (a < b) ? a : b; }
template<class T> inline T tmax(T a, T b) { return (a > b) ? a : b; }
template<class T> inline void amax(T &a, T b) { if (b > a) a = b; }
template<class T> inline void amin(T &a, T b) { if (b < a) a = b; }
template<class T> inline T tabs(T a) { return (a > 0) ? a : -a; }
template<class T> T gcd(T a, T b) { while (b != 0) { T c = a; a = b; b = c % b; } return a; }
int main(int argc, char *argv[]) {
ios_base::sync_with_stdio(false);
int n, d;
cin >> n >> d;
vector<int> a(n);
map<int, int> mp;
REPU(i, 0, n) {
cin >> a[i];
mp[a[i]] = 1;
}
int ans = 0;
REPU(i, 0, n) {
if (mp.count(a[i] - d) > 0 && mp.count(a[i] + d) > 0) ans++;
}
cout << ans << endl;
return 0;
}
Beautiful Triplets C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int[] a = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int d = a[1];
int count = 0;
List<int> seq = Console.ReadLine().Split(' ').Select(Int32.Parse).ToList();
foreach(int s in seq)
{
if(seq.Contains(s+d) && seq.Contains(s+d+d)) {count++;}
}
Console.WriteLine(count);
}
}
Beautiful Triplets Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* 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
*/
public static int beautifulTriplets(int d, List<Integer> arr) {
Map<Integer, Boolean> booleanMap = new HashMap<>();
arr.forEach(integer -> {
booleanMap.put(integer, true);
});
int t = 0;
for (Integer integer : arr) {
if (Boolean.TRUE.equals(booleanMap.get(integer + d)) && Boolean.TRUE.equals(booleanMap.get(integer + d + d))) {
t++;
}
}
return t;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int d = Integer.parseInt(firstMultipleInput[1]);
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
int result = Result.beautifulTriplets(d, arr);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Beautiful Triplets JavaScript Solution
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
const [[_, d], n] = _input.split('\n').map(s => s.split(' ').map(Number));
let cnt = 0;
for(let i=0; i<n.length-2;i++) {
const ii = n[i];
for(let j=i+1; j<n.length-1;j++) {
const jj = n[j];
if (jj-ii === d) {
for(let k=j+1; k<n.length;k++) {
const kk = n[k];
if (kk-jj === d) {
cnt++;
}
}
}
}
}
console.log(cnt)
});
Beautiful Triplets Python Solution
from collections import defaultdict
n, d = [int(i) for i in input().strip().split()]
arr = [int(i) for i in input().strip().split()]
num_to_index = defaultdict(list)
for i, num in enumerate(arr):
num_to_index[num].append(i)
results = []
d2 = d + d
for num in sorted(num_to_index):
a,b,c = num, num+d, num+d2
if b in num_to_index and c in num_to_index:
mx = max(num_to_index[c])
mn = min(num_to_index[a])
if mx > mn and any(mx > i > mn for i in num_to_index[b]):
results.append((a,b,c))
print(len(results))
Other Solutions