Skip to content
Advertisement

Given N integers, count the number of pairs of integers whose difference is K

I was given an array like this array(1,5,3,4,2);
Say k=2, I’m supposed to find out the count of pairs whose difference is 2. In this case it should return 3 because 5-3, 4-2, 3-1

Here’s what I have tried. It works fine I’m looping through the array twice O(n^2) complexity, I’m wondering if there is a better way to achieve this.

JavaScript

Thanks

Advertisement

Answer

Ofcourse, There are many ways:

Using Sorting:

JavaScript

one with complexity of O(n) is :

JavaScript

Anyways you can refer to this link for more info.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement