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 ofB
, in eachA
andC
- counting using binary search
Implementation
1function 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}1718function 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}
Comments
Loading comments...
Tags
hackerrank
binary search
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.