Search code examples
algorithmsortinghashtable

Find pairs of integers from an array having difference of k (using hash tables only)


Given an array of distinct integer values, count the number of pairs of integers that have difference k. For example, given the array {1, 7, 5, 9, 2, 12, 3} and the difference k = 2.

Need solution using hash tables only.


Solution

  • Put all the numbers into a hash table. Then, for each of the original numbers n check if n+k is in the hash table. Count, how many hits you have found.