Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Hackerearth Pairs Having Similar Elements problem solution

YASH PAL, 31 July 202413 February 2026
In this HackerEarth Pairs Having Similar Elements problem solution, we have given an array, A, having N integers A1,A2,…,An.Two elements of the array Ai and Aj are called similar if Ai = Aj + 1 or Aj = Ai + 1.
 
 
Hackerearth Pairs Having Similar Elements problem solution

 

 

Hackerearth Pairs Having Similar Elements problem solution.

#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin>>n;
int* a= new int[n];
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
ll ans=0;
ll ct=1,ctdis=1;
for(int i=1;i<n;i++){
if(a[i]==a[i-1]){
ct++;
}
else if(a[i]==(a[i-1]+1)){
ct++;
ctdis++;
}
else{
if(ct>=2&&(ctdis>=2)){
ans+=(((ct)*(ct-1))/2);
}
ct=1;
ctdis=1;
}
}
if(ct>=2&&(ctdis>=2)){
ans+=(((ct)*(ct-1))/2);
}
cout<<ans<<endl;

return 0;
}
 

Second solution

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define REP(i,n) for(i=1;i<=n;i++)
#define FOR(i,a,b) for(i=a;i<=b;i++)
#define all(v) v.begin(),v.end()
#define F first
#define S second
#define vl vector<LL>
#define itr ::iterator it
#define lb lower_bound
#define ub upper_bound
#define LL long long
#define ULL unsigned long long
#define ret return
LL n,i,j,ans = 0;
LL a[10000000] ;
void f(LL x)
{
ans += (x * (x-1))/2 ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin>>n ;
assert(n>=1 and n<=1000000) ;
REP(i,n)
{ cin>>a[i] ;
assert(a[i]>=-1000000000 and a[i]<=1000000000) ;
}
sort(a+1,a+1+n) ;

LL x = 0 ;
for(i=1;i<=n;i++)
{ LL k = 0,l = 0 ;
for(j=i+1;j<=n;j++)
{ k = max(k,a[j]-a[j-1]) ;
if(k==1) l++ ;
if(k>1) break ;
}
if(l)
f(j-i) ;
i = j - 1 ;
}
cout<<ans<<endl ;

}
 
coding problems solutions HackerEarth HackerEarth

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes