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 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 | |
} |
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 | |
} |