# Hackerrank: Triple Sum Solution

## Approach

First, remove duplicated elements in each array to avoid duplicated triplet

Then

Option 1: brute force, exhausive search by 3 nested loop to find triplet

Option 2:

• iterate through each element of
B
, count the number of elements, which are less than or equal to the iterated element of
B
, in each
A
and
C
• counting using binary search

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function binarySearch(A, x) {2  let N = A.length3  let begin = 04  let end = N - 15  let result = -16  while (begin <= end) {7    let mid = Math.floor((begin + end) / 2)8    if (A[mid] <= x) {9      begin = mid + 110      result = mid11    } else {12      end = mid - 113    }14  }15  return result + 116}17
18function triplets(a, b, c) {19  const ascSortThenUnique = arr =>20    Array.from(new Set(arr)).sort((a, b) => a - b)21  a = ascSortThenUnique(a)22  b = ascSortThenUnique(b)23  c = ascSortThenUnique(c)24  let res = 025  for (const q of b) {26    res += binarySearch(a, q) * binarySearch(c, q)27  }28  return res29}```

hackerrank

binary search

## Next Post

Hackerrank: Pairs

Jan 30, 2021

Search Posts