Skip to content

Instantly share code, notes, and snippets.

@taravancil
Last active September 28, 2016 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taravancil/d740b51f6ee0ba658a3fe47217dcf3b6 to your computer and use it in GitHub Desktop.
Save taravancil/d740b51f6ee0ba658a3fe47217dcf3b6 to your computer and use it in GitHub Desktop.
Two solutions for finding pairs of numbers in a list with a given difference. See https://www.hackerrank.com/challenges/pairs for more test cases.
function onePointer (input) {
const lines = input.split('\n')
const k = Number(lines[0].split(' ')[1])
let nums = lines[1].split(' ').map(x => Number(x))
let count = 0
// Sort the numbers in order to limit the number of required comparisons
nums.sort((a, b) => a - b)
// For each element, calculate the difference between it and subsequent elements up to
// the point at which their difference is equal to K. O(n^2)
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
// Since nums is sorted, we can always subtract the smaller number from the larger number,
// so diff is always positive
let diff = nums[j] - nums[i]
if (diff === k)
count ++
break
}
// If diff is greater than K, we know that diff will greater than K for all subsequent elements
else if (diff > k) {
break
}
}
return count
}

Given the input

5 2
1 5 3 4 2

where 5 is the number of elements in the list consider, 2 is k, and 1 5 3 4 2 is the list to consider, the expected output is 3.

function set (input) {
const lines = input.split('\n')
const k = Number(lines[0].split(' ')[1])
let nums = lines[1].split(' ').map(x => Number(x))
let count = 0
const nums_set = new Set(nums)
// We only need to loop through the set once, so this runs in linear time (O(n)). Woohoo!
nums_set.forEach(num => {
// Find the difference between k and num. If the difference is in the set,
// then there exists a pair with difference k.
if (nums_set.has(num - k)) {
count ++
}
})
return count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment