Hackerrank Pairs Python solution

Wenwei Xu
1 min readSep 2, 2019

--

You will be given an array of integers and a target value k. Determine the number of pairs of array elements that have a difference equal to k.

Link: https://www.hackerrank.com/challenges/pairs/problem

Thinking process and complexity:

We will create a dictionary to save the elements, while looking for pairs from the dictionary at the same time. This way, we are saving time O(n), but we do consume some memory O(n) for the dictionary.

Another idea is to sort the array, and then use two pointers moving in the same direction to find pairs. This way, we will only use O(1) memory, while the sorting will cost time O(nlogn).

Python 3 Solution:

Hash map solution:

Two pointers solution:

Comments and suggestions welcome!

--

--