Hackerrank: Pairs Solution

1function binarySearch(A, x) {
2 const N = A.length
3 let begin = 0
4 let end = N - 1
5 let result = -1
6 while (begin <= end) {
7 let mid = Math.floor((begin + end) / 2)
8 if (A[mid] === x) {
9 result = mid
10 break
11 }
12 if (A[mid] > x) {
13 end = mid - 1
14 } else if (A[mid] < x) {
15 begin = mid + 1
16 }
17 }
18 return result
19}
20
21function pairs(k, arr) {
22 const sortedArr = Array.from(arr).sort((a, b) => a - b)
23 let count = 0
24 for (const a of arr) {
25 if (binarySearch(sortedArr, a + k) !== -1) {
26 count++
27 }
28 }
29 return count
30}

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.

Next Post

Hackerrank: Minimum Absolute Difference in an Array

HoningJS

Search Posts