Count valid pairs in the array satisfying given conditions in C++

C++Server Side ProgrammingProgramming

We are given with an array arr[] of N elements. The goal is to find the count of all valid pairs (Arr[i],Arr[j]) that follow certain conditions. Pairs Arr[i],Arr[j] invalid if −

  • Arr[i]==Arr[j]
  • Arr[i]+Arr[j] is even
  • i+j<120

NoteArr[i],Arr[j] and Arr[j],Arr[i] will be counted as one pair. Valid pair has i!=j Let’s understand with examples.


Arr[]= { 3,2,1,2,4,3 } N=4


Count of valid pairs: 2


Valid pairs are −

Arr[0] & Arr[4] → (3,3) here Arr[i]==Arr[j] & 3+3 is even also i!=j and i+j<120
Arr[1] & Arr[3] → (2,2) here Arr[i]==Arr[j] & 2+2 is even also i!=j and i+j<120


Arr[]= { 1,2,3,4,5,6 } N=6


Count of valid pairs: 0


No repetition of elements. No pair of type ( a,a ) possible where i!=j.

Approach used in the below program is as follows

  • We take an integer array Arr[] initialized with random numbers.
  • Take a variable n which stores the length of Arr[].
  • Function countPairs(int arr[], int n) takes an array, its length as input and returns the pairs which are valid and meet desired conditions.
  • Traverse array using two for loops for each element of the pair.
  • Outer Loop from 0<=i<n-1, inner loop i<j<n
  • Calculate sum of arr[i], arr[j] assum=(arr[i]+aar[j]).
  • To check if a pair is valid. Compare if i!=j and sum%2==0 also i+j<120.
  • Now check if arr[i]==arr[j]. Increment count.
  • At the end of all loops count will have a total number of pairs that are valid
  • Return the count as result.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int countPairs(int arr[], int n){
   int count=0;
   for(int i=0;i<n;i++){
      for(int j=i+1;j<n;j++) //j=i+1 we don't have to check i!=j{
         int sum=arr[i]+arr[j];
         //valid pairs have i!=j
         if( sum%2==0 && i+j<120){
            if( arr[i]==arr[j] ) //valid pair{
               cout<<endl<<" a:"<<arr[i]<<"b: "<<arr[j];
   return count;
int main(){
   int arr[] = {1,2,3,2,4,1,4 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout <<endl<<"Valid pairs in array:"<<countPairs(arr, n);
   return 0;


Valid pairs in array:
a:1b: 1
a:2b: 2
a:4b: 43
Updated on 16-Sep-2020 10:00:45