Table of contents
1.
Introduction
2.
Problem Statement
3.
Solution
4.
Complexity Analysis
5.
FAQs
5.1.
What is a copy constructor?
5.2.
What’s the key difference between exception and error in java?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Count Pairs

Author Akash Nagpal
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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.

 

Solution

 

Java Solution

import java.util.*;
public class Main {
    public static int pairs(int a[], int n , int z)
    {
        int c=0,i;
        for(i=0;i<n;i++)
        {
            int temp=a[i];
            int id1=i; int id2=i;
            if(i==0)
            {
                while(a[id2+1]==temp)
                id2++;
                if(a[id2+1]<=temp+z && a[id2+1]>=temp-z)
                c++;
            }
            else if(i<n-1)
            {
                while(a[id2+1]==temp)
                id2+=1;
                while(a[id1-1]==temp)
                id1-=1;
                if(((a[id1-1]<=temp+z) && (a[id1-1]>=temp-z)) || (
(a[id2+1]<=temp+z) && (a[id2+1]>=temp-z)))
                c+=1;
            }
            else
            {
                while(a[id1-1]==temp)
                id1-=1;
                if(a[id1-1]<=aa+z && a[id1-1]>=aa-z)
                c+=1;
            }
        }
        return c;
    }
    public static void main(String[] args) throws Exception {
        // Your code  here!
        Scanner sc= new Scanner(System.in);
        // System.out.println("XXXXXXXX")
        int n,k,i,s=0; 
        n=sc.nextInt();
        k=sc.nextInt();
        int a[]= new int [n];
        
        for(i=0;i<n;i++) a[i]=sc.nextInt();
        Arrays.sort(a);
        System.out.print(pairs(a,n,k));
    }
}

Output

3 2
1 3 5
3

 

 

C++ Solution

#include <bits/stdc++.h>
using namespace std;
int pairs(int elementlst[],int n,int z){
 int ans_count=0;
  for(int i=0;i<n;i++){
    int temp=elementlst[i];
    int id1=i;
    int id2=i;
    if(i==0){
      while(elementlst[id2+1]==temp)
         id2+=1;
      if(elementlst[id2+1]<=temp+z && elementlst[id2+1]>=temp-z)
     ans_count+=1;
    }
    else if(i<n-1){
      while(elementlst[id2+1]==temp)
        id2+=1;
      while(elementlst[id1-1]==temp)
        id1-=1;
      if(((elementlst[id1-1]<=temp+z) && (elementlst[id1-1]>=temp-z)) || ((elementlst[id2+1]<=temp+z) && (elementlst[id2+1]>=temp-z)))
     ans_count+=1;
    }
    else{
      while(elementlst[id1-1]==temp)
        id1-=1;
      if(elementlst[id1-1]<=temp+z && elementlst[id1-1]>=temp-z)
     ans_count+=1;
    }
  }
  return ans_count;
}
int main() {
int n,z;
cin>>n>>z;
int elementlst[n];
for(int i=0;i<n;i++){
    cin>>elementlst[i];
}
sort(elementlst,elementlst+n);
cout<<pairs(elementlst,n,z);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

3 2
1 3 5
3
You can also try this code with Online C++ Compiler
Run Code

 

Python Solution

n, k = map(int, input().split())
a = set()
a = set(map(int, input().split()))
a = list(a)
if n==1:
    print("0")
else:
    a = sorted(a)
c = 0
for i in range(1, len(a)-1):
    if a[i]-a[i-1]>k and a[i+1]-a[i]>k :
        c += 1
if a[1]-a[0]>k:
    c+=1
if a[len(a)-1]-a[len(a)-2]>k:
    c +=1
print(n-c)

Output

3 2
1 3 5
3

Complexity Analysis

  • Time Complexity: We have solved the given coding problem in O(N2) time complexity.
  • Space Complexity: O(1) will be the space complexity because we haven't used any extra space other than variables.

FAQs

What is a copy constructor?

A copy function Object() is a member function that uses another object of the same class to initialize an object.

What’s the key difference between exception and error in java?

The error indicates a problem, which is usually caused by a lack of system resources, and our application isn't set up to identify such problems. Exceptions are mistakes that can occur both during execution and compilation. It's typically encountered in code produced by programmers. The Java Throwable class, which is part of the java package, has two subclasses: exception and error.

Conclusion

In this article, we have extensively discussed the TCS Codevita interview questions on Count Pairs. We tried to cover it with some examples.

You can look at more exciting blogs and articles curated by the coding ninja's team by visiting Library.

We hope that this blog has helped you enhance your knowledge regarding Count pairs and other similar types of problems and if you would like to learn more, you can try to solve Count Pairs 

Do upvote our blog to help other ninjas grow. 

Happy Coding!

 

Live masterclass