Introduction
In this article, we’ll write a program to count pairs and print happy elements from an array. This coding problem is one of the TCS Codevita's previous year questions.
TCS CodeVita is a competition for engineering and science students to learn how to code and improve their programming abilities using real-world computing. The event attempts to find talent as well as provide the student community a chance to be recognised by their peers.
Now let us understand the problem statement clearly.
Problem Statement
Find the number of happy elements from the array given an integer K and an integer array A[].
A happy element is an element if there exists at least one element whose difference is less than K where K would be the given integer.
This means that an element X is happy if there is another element in the range [X-K, X+K] other than X itself.
Constraints
0 <= A[i] <= 10^9
0 <= K <= 10^5
1 <= N <= 10^5
Input
The first line of the input will contain two integers: N and K, where N is the size of the array A [] and K is an int number as mentioned above. The second line of input contains N integers separated by space.
Output
Print an integer indicating the number of happy elements in total.
Now let us understand the statement with the help of an example.
Example 1
Input
6 3
5 5 7 9 15 2
Output
5
Explanation
Other than 15, every other element from A[] has at least one element in the range of [X-3, X+3]. So, they all are happy elements. Since these are a total of five elements, the output is 5.
Example 2
Input
3 2
1 3 4
Output
3
Explanation
All the elements have at least one element in the range of [X-2, X+2]. Hence they are all happy elements. Since the total count is 3, therefore the output will be 3.




