Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone

Hackerearth Pairs Having Similar Elements problem solution

YASH PAL, 31 July 2024
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

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes