Here in this problem, we are given 3 arrays a, b and c of different sizes, find the number of distinct triplets(p,q,r) where p is an element of a, written as
p \;\epsilon \;a ,\;\; q\epsilon b \;\; and\;\;r\epsilon c satisfying the criteria:
p\leq q and q\geq r Read the full question on hackerrank

Explanation Video:

 

Youtube Channel partner: CodingCart
Mentor: Satyendra Jaiswal
Langauge: Python

Source Code:  for triplets function


# Complete the triplets function below.
def triplets(a, b, c):
    a=sorted(set(a))
    b=sorted(set(b))
    c=sorted(set(c))
    count=m=n=0
    for v in b:
        while m < len(a) and a[m]<=v:   #p<=q
            m+=1
        while n < len(c) and c[n]<=v:  #r<=q
            n+=1 
        count+=m*n  
    return count         
coming soon…
coming soon…

Full Source Code:


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the triplets function below.
def triplets(a, b, c):
    a=sorted(set(a))
    b=sorted(set(b))
    c=sorted(set(c))
    count=m=n=0
    for v in b:
        while m < len(a) and a[m]<=v:   #p<=q
            m+=1
        while n < len(c) and c[n]<=v:  #r<=q
            n+=1 
        count+=m*n  
    return count         

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    lenaLenbLenc = input().split()

    lena = int(lenaLenbLenc[0])

    lenb = int(lenaLenbLenc[1])

    lenc = int(lenaLenbLenc[2])

    arra = list(map(int, input().rstrip().split()))

    arrb = list(map(int, input().rstrip().split()))

    arrc = list(map(int, input().rstrip().split()))

    ans = triplets(arra, arrb, arrc)

    fptr.write(str(ans) + '\n')

    fptr.close()

coming soon…
coming soon…

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our Youtube Channel.

This post is in partnership with CodingCart.