Count pairs formed by distinct element sub-arrays in C++


We are given an array arr[] containing integer elements. The goal is to find the count of pairs that can be formed by elements of sub-arrays of arr[] such that each subarray has only distinct elements. If the array is [ 1,2,2,3,3 ] then subarrays with distinct elements only will be [ 1,2 ] and [ 2,3 ]. And pairs will be (1,2) and (2,3) hence count of pairs is 2.

Let us understand with examples

Input − arr[] = {1,2,5,3 }

Output − Count of pairs formed by distinct element sub-arrays are − 6

Explanation − The subarrays with distinct elements are : [ 1,2,5, 3], possible pairs (1,2), (1,3), (1,5), (2,5), (2,3), (5,3)

Total 6 pairs.

Input − arr[] = {1,2,1,2,3}

Output − Count of pairs formed by distinct element sub-arrays are − 5

Explanation − The subarrays with distinct elements are −

[1,2] - pairs: (1,2)
[2,1] - pairs: (2,1)
[1,2,3] - pairs : (1,2), (2,3), (1,3)
Total pairs : 5

The approach used in the below program is as follows

  • Take an integer array as input.

  • Function distinct_pairs(int arr[], int size) takes the array and returns the Count pairs formed by distinct element sub-arrays.

  • Take the initial count as 0. Take variables start=end=0.

  • Take a vector check(size, false) to mark elements in the window.

  • Start loop WHILE till start is less than size

  • Inside the loop, start another loop WHILE till start less than size AND check[arr[star]] = 0 then set count as start - end and set check[arr[start]] as true and also increment the start by 1.

  • Start Loop WHILE till end less than start AND start is not equal to the size AND check[arr[start]] = true then set check[arr[end]] = false and also increment the end by 1.

  • Return the count

  • Print the result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int distinct_pairs(int arr[], int size){
   int count = 0;
   int start = 0;
   int end = 0;
   vector<bool> check(size, false);
   while (start < size){
      while (start < size && !check[arr[start]]){
         count += (start - end);
         check[arr[start]] = true;
         start++;
      }
      while (end < start && (start != size && check[arr[start]])){
         check[arr[end]] = false;
         end++;
      }
   }
   return count;
}
int main(){
   int arr[] = {5, 1, 8, 2, 1, 7, 9, 1};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs formed by distinct element sub-arrays are: "<< distinct_pairs(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of pairs formed by distinct element sub-arrays are: 17

Updated on: 03-Dec-2020

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements