Triple Sum — HackerRank Medium

iAwale
2 min readMar 18, 2020

Link to problem

Link to solution

The problem requires us to find number of distinct triplets from three sets of arrays. The brute force method is easy to implement here: Nest 3 for-loops and put in the condition which checks if the element of array b is greater or equal to the other two elements of the arrays a and c respectively. It works but is not time efficient and HackerRank will not let the code pass its test.

One thing to keep in mind is the condition: element of b is greater than the other two elements in a triplet. This tells us that we can make the iterative loop for b as the parent loop.

Then if we sort the arrays, it would mean that the values we have counted for the previous members of b can be reused as all the values that are lower than b[i] are lower than b[i+1] as well. Thus this greatly reduces the time required. This is also why we use a while loop in the child loop instead of for.

We use distinct() to make sure the triplets are not repeated.

For those of you wondering why we count the values less than or equal to the element from b:

Once we check for the count in both array a and b, we can multiply those two counts to get the number of possible triplets for that element from array b. We repeat this for all elements of b to get the total count.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet

Write a response