Hackerrank: Pairs Solution
1function binarySearch(A, x) {2 const 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 result = mid10 break11 }12 if (A[mid] > x) {13 end = mid - 114 } else if (A[mid] < x) {15 begin = mid + 116 }17 }18 return result19}2021function pairs(k, arr) {22 const sortedArr = Array.from(arr).sort((a, b) => a - b)23 let count = 024 for (const a of arr) {25 if (binarySearch(sortedArr, a + k) !== -1) {26 count++27 }28 }29 return count30}
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.