Beautiful Triplets HackerRank Solution in C, C++, Java, Python

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 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].

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

3

 

Beautiful Triplets HackerRank Solution in C

#include<stdio.h>
int main(void){
    int n,d;
    scanf("%d %d",&n,&d);
    int a[n];
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    int s=0;
    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(a[j]-a[i]!=d) continue;
            for(int k=j+1;k<n;k++){
                if(a[j]-a[i]==a[k]-a[j] && a[k]-a[j]==d)s++;
            }
        }
    }
    printf("%d",s);
    return 0;
}

 

Beautiful Triplets HackerRank Solution in C++

#include <iostream>
#include <cstring>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <bitset>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <assert.h>
using namespace std;

void smain();
int main(){
#ifdef TASK
    freopen(TASK".in","rt",stdin);
    const clock_t start = clock();
#endif
    smain();
#ifdef TASK
    cerr << "\nTotal Execution Time: " << float( clock () - start ) /  CLOCKS_PER_SEC << endl;
#endif
    return 0;
}

#ifndef M_PI
#define M_PI 3.14159265358979311599796346854418516
#endif
#define forn(i,n) for (int i=0;i<n;i++)
#define rforn(i,n) for (int i=n-1;i>=0;i--)
#define int long long
#define LL __int128
#define mp(a,b) make_pair(a,b)
#define INF 2305843009213693951LL
#define MOD 1000000007
#define EPS 1E-6
#define N 200001

int n, d;
int a[N];


void smain() {
    for (; cin >> n >> d; ) {
        forn(i, n) cin >> a[i];
        int res = 0;
        map<int, int> l, r;
        forn(i, n) r[a[i]] += 1;
        forn(i, n) {
            r[a[i]] -= 1;
            res += l[a[i]-d] * r[a[i]+d];
            l[a[i]] += 1;
        }
        cout << res << '\n';
    }
}

 

Beautiful Triplets HackerRank Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int d = sc.nextInt();
        int[] a = new int[n];
        HashSet<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            set.add(a[i]);
        }
        
        int ans = 0;
        
        for (int i = 0; i < n; i++) {
            if (set.contains(a[i]+d)&&set.contains(a[i]+2*d))
                ans++;
        }
        
        System.out.println(ans);
    }
}

 

Beautiful Triplets HackerRank Solution in Python

rr = raw_input
rrM = lambda: map(int, rr().split())
N,D = rrM()
A = rrM()
#beau if i<j<k , ak - aj = aj - ai = d
from collections import defaultdict as ddic
seenL = ddic(int)
seenR = ddic(int)

for i in xrange(N):
    for j in xrange(i+1,N):
        if A[j]-A[i] == D:
            seenL[j] += 1
            seenR[i] += 1
ans = 0
for i in xrange(N):
    ans += seenL[i] * seenR[i]
print ans

 

Beautiful Triplets HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;

public class Solution {
    #region Stable
    public delegate string ReadLine();
    public delegate void WriteLine(object line);

    static public ReadLine read = delegate { return Console.ReadLine(); };
    static public WriteLine write = (x) => Console.WriteLine(x);

    static public List<int> GetIntsLine() {
        return read().Split(' ').Select(x => int.Parse(x)).ToList();
    }

    static public List<string> GetStringsLine() {
        return read().Split(' ').ToList();
    }


    static public List<long> GetLongsLine() {
        return read().Split(' ').Select(x => long.Parse(x)).ToList();
    }
    #endregion

    static public void Main(String[] args) {
        var nd = GetIntsLine();
        var ns = GetIntsLine();
        var n = nd[0];
        var d = nd[1];

        var dic = ns.Select((x,i) => Tuple.Create(x,i)).ToDictionary(x => x.Item1, x=> x);

        var count = 0;
        for (int i = 0; i < ns.Count; i++) {
            var number = ns[i];

            Tuple<int,int> mid = null;
            dic.TryGetValue(number+d,out mid);
            if (mid==null) continue;
            if (mid.Item2 <= i) continue;
            Tuple<int, int> last = null;
            dic.TryGetValue(mid.Item1 + d, out last);
            if (last==null) continue;
            if (last.Item2 <= i) continue;
            count++;
        }
        write(count);
    }
}

 

Attempt Beautiful Triplets HackerRank Challenge

Link – https://www.hackerrank.com/challenges/beautiful-triplets/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/minimum-distances-hackerrank-solution/

Leave a Comment