Given an array of N integers, the task is to find all pairs with an absolute difference less than K.
NOTE: Pair (i, j) is considered same as (j, i)
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 ≤ 10^{5}
0 ≤ K ≤ 10^{4}
1 ≤ A[i] ≤ 10^{5}

Source: geeksforgeeks | Difficulty: EASY
Tags: Data structures

Starter code: #User function Template for python3

class Solution:
    def countPairs(self,a, n, k): 
          
        # Complete the function

Solutions:
class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		output = 0
		j = 0
		for i in range(n):
			while a[i] - a[j] >= k:
				j += 1
			output += i - j
		return output


class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		c = 0
		i = 1
		j = 0
		while i < n:
			while a[i] - a[j] >= k:
				j += 1
			if a[i] - a[j] < k:
				c += i - j
			i += 1
		return c


class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		l = 1
		r = 0
		count = 0
		while l < n:
			while a[l] - a[r] >= k:
				r += 1
			if a[l] - a[r] < k:
				count += l - r
			l += 1
		return count


import bisect

class Solution:

	def countPairs(self, arr, n, k):
		arr.sort()
		ans = 0
		for i in range(n):
			idx = bisect.bisect_left(arr, k + arr[i])
			ans += idx - i - 1
		return ans


class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		count = 0
		low = 0
		high = 1
		while high < n:
			while abs(arr[high] - arr[low]) >= k:
				low += 1
			if abs(arr[high] - arr[low]) < k:
				count += high - low
			high += 1
		return count


class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		s = 0
		total = 0
		for i in range(1, n):
			while s < i and a[i] - a[s] >= k:
				s += 1
			total += i - s
		return total


class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		(ans, diff) = (0, 0)
		(r, l) = (0, 0)
		while r < n:
			diff = a[r] - a[l]
			if diff < k:
				ans += r - l
				r += 1
			else:
				l += 1
		return ans


class Solution:

	def countPairs(self, a, n, k):
		nums = a
		nums.sort()
		res = 0
		i = 0
		j = 1
		while j < len(nums):
			if i == j:
				j += 1
				continue
			diff = nums[j] - nums[i]
			if diff < k:
				res += j - i
				j += 1
			else:
				i += 1
		return res


import bisect

class Solution:

	def countPairs(self, a, n, k):
		a.sort()
		count = 0
		for i in range(n - 1):
			j = bisect.bisect_left(a, a[i] + k)
			count += j - i - 1
		return count