X

DAYS

:

HOUR

:

MINS

:

SEC

Copied to Clipboard
Pairs with Difference less than K
Easy Accuracy: 60.92% Submissions: 562 Points: 2

Given an array of N integers, the task is to find all pairs with a difference less than K.

Example 1:

Input : Arr[] = {1, 10, 4, 2}, K = 3
Output : 2
Explanation:
we have an array a[] = {1, 10, 4, 2} and 
K = 3 We can make only two pairs with a 
difference of less than 3.
(1, 2) and (4, 2). So, the answer is 2.

Example 2:

Input : Arr[] = {2, 3, 4}, K = 5
Output : 3


Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function countPairs() that takes an array (arr), sizeOfArray (n), the integer K, and return the number of pairs whose difference is less than K. The driver code takes care of the printing.

Expected Time Complexity: O(NLog(n)).
Expected Auxiliary Space: O(1).

 

Constraints:
2 ≤ N ≤ 105
0 ≤ K ≤ 104
1 ≤ A[i] ≤ 105

We are replacing the old Disqus forum with the new Discussions section given below.
Click here to view old Disqus comments.


to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Pairs with Difference less than K

Output Window