Count pairs formed by distinct element sub-arrays
Last Updated :
01 Jul, 2022
Given an array, count number of pairs that can be formed from all possible contiguous sub-arrays containing distinct numbers. The array contains positive numbers between 0 to n-1 where n is the size of the array.
Examples:
Input: [1, 4, 2, 4, 3, 2]
Output: 8
The subarrays with distinct elements
are [1, 4, 2], [2, 4, 3] and [4, 3, 2].
There are 8 pairs that can be formed
from above array.
(1, 4), (1, 2), (4, 2), (2, 4), (2, 3),
(4, 3), (4, 2), (3, 2)
Input: [1, 2, 2, 3]
Output: 2
There are 2 pairs that can be formed
from above array.
(1, 2), (2, 3)
The idea is to use Sliding Window for the given array. Let us use a window covering from index left to index right and an Boolean array visited to mark elements in current window. The window invariant is that all elements inside the window are distinct. We keep on expanding the window to the right and if a duplicate is found, we shrink the window from left till all elements are distinct again. We update the count of pairs in current window along the way. An observation showed that in an expanding window, number of pairs can be incremented by value equal to window size – 1.
For example,
Expanding Window Count
[1] Count = 0
[1, 2] Count += 1 pair
i.e. (1, 2)
[1, 2, 3] Count += 2 pairs
i.e. (1, 3) and (2, 3)
[1, 2, 3, 4] Count += 3 pairs
i.e. (1, 4), (2, 4)
and (3, 4)
So, total Count for above window of size 4 containing distinct elements is 6. Nothing need to be done when the window is shrinking.
Below is the implementation of the
C++
#include <bits/stdc++.h>
using namespace std;
int countPairs( int arr[], int n)
{
int count = 0;
int right = 0, left = 0;
vector< bool > visited(n, false );
while (right < n)
{
while (right < n && !visited[arr[right]])
{
count += (right - left);
visited[arr[right]] = true ;
right++;
}
while (left < right && (right != n &&
visited[arr[right]]))
{
visited[arr[left]] = false ;
left++;
}
}
return count;
}
int main()
{
int arr[] = {1, 4, 2, 4, 3, 2};
int n = sizeof arr / sizeof arr[0];
cout << countPairs(arr, n);
return 0;
}
|
Java
class GFG
{
static int countPairs( int arr[], int n)
{
int count = 0 ;
int right = 0 , left = 0 ;
boolean visited[] = new boolean [n];
for ( int i = 0 ; i < n; i++)
visited[i] = false ;
while (right < n)
{
while (right < n && !visited[arr[right]])
{
count += (right - left);
visited[arr[right]] = true ;
right++;
}
while (left < right && (right != n &&
visited[arr[right]]))
{
visited[arr[left]] = false ;
left++;
}
}
return count;
}
public static void main(String args[])
{
int arr[] = { 1 , 4 , 2 , 4 , 3 , 2 };
int n = arr.length;
System.out.println( countPairs(arr, n));
}
}
|
Python3
def countPairs(arr, n):
count = 0
right = 0
left = 0
visited = [ False for i in range (n)]
while (right < n):
while (right < n and
visited[arr[right]] = = False ):
count + = (right - left)
visited[arr[right]] = True
right + = 1
while (left < right and (right ! = n and
visited[arr[right]] = = True )):
visited[arr[left]] = False
left + = 1
return count
if __name__ = = '__main__' :
arr = [ 1 , 4 , 2 , 4 , 3 , 2 ]
n = len (arr)
print (countPairs(arr, n))
|
C#
using System;
class GFG
{
static int countPairs( int []arr, int n)
{
int count = 0;
int right = 0, left = 0;
bool [] visited = new bool [n];
for ( int i = 0; i < n; i++)
visited[i] = false ;
while (right < n)
{
while (right < n && !visited[arr[right]])
{
count += (right - left);
visited[arr[right]] = true ;
right++;
}
while (left < right && (right != n &&
visited[arr[right]]))
{
visited[arr[left]] = false ;
left++;
}
}
return count;
}
public static void Main()
{
int [] arr = {1, 4, 2, 4, 3, 2};
int n = arr.Length;
Console.Write( countPairs(arr, n));
}
}
|
Javascript
<script>
function countPairs(arr,n)
{
let count = 0;
let right = 0, left = 0;
let visited = new Array(n);
for (let i = 0; i < n; i++)
visited[i] = false ;
while (right < n)
{
while (right < n && !visited[arr[right]])
{
count += (right - left);
visited[arr[right]] = true ;
right++;
}
while (left < right && (right != n &&
visited[arr[right]]))
{
visited[arr[left]] = false ;
left++;
}
}
return count;
}
let arr=[1, 4, 2, 4, 3, 2];
let n = arr.length;
document.write( countPairs(arr, n));
</script>
|
Time Complexity: The complexity might look O(n^2) as 2 while loop are involved but note that left and right index are changing from 0 to N-1. So overall complexity is O(n + n) = O(n). Auxiliary space required in above solution is O(n) as we are using visited array to mark elements of the current window.
Similar Reads
Count of distinct pair sum in given Array
Given an array arr[] of size N, the task is to find the total number of unique pair sums possible from the array elements. Examples: Input: arr[] = {6, 1, 4, 3}Output: 5Explanation: All pair possible are {6, 1}, {6, 4}, {6, 3}, {1, 4}, {1, 3}, {4, 3}. Sums of these pairs are 7, 10, 9, 5, 4, 7. So un
4 min read
Count Distinct ( Unique ) elements in an array
Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples: Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and ru
15 min read
Count distinct elements in an array in Python
Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Count subarrays having total distinct elements same as original array
Given an array of n integers. Count the total number of sub-arrays having total distinct elements, the same as that of the total distinct elements of the original array. Examples: Input : arr[] = {2, 1, 3, 2, 3} Output : 5 Total distinct elements in array is 3 Total sub-arrays that satisfy the condi
11 min read
Count unequal element pairs from the given Array
Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] != arr[j] and i < j.Examples: Input: arr[] = {1, 1, 2} Output: 2 (1, 2) and (1, 2) are the only valid pairs.Input: arr[] = {1, 2, 3} Output: 3Input: arr[] = {1, 1, 1} Output: 0 Recommended
10 min read
Counting Distinct Arrays by Removal and Concatenation of Elements
Given an array arr[] of length N, the task is to create an array res[] of length N where each element res[i] represents the count of distinct arrays obtained by applying the below operation on prefix arr[1, i] for (1 <= i <= N): Select three distinct indices let say i1, i2 and i3 such that (1
15 min read
Count of distinct index pair (i, j) such that element sum of First Array is greater
Given two arrays a[] and b[], both of size N. The task is to count the number of distinct pairs such that (a[i] + a[j] ) > ( b[i] + b[j] ) subject to condition that (j > i). Examples: Input: N = 5, a[] = {1, 2, 3, 4, 5}, b[] = {2, 5, 6, 1, 9} Output: 1 Explanation: Only one such pair exists an
13 min read
Count Subarrays With At Most K Distinct Elements
Given an array arr[] and an integer k, the task is to find the count of subarrays such that each subarray has at most k distinct elements. Examples: Input: arr[] = [1, 2, 2, 3], k = 2 Output: 9Explanation: Subarrays with at most 2 distinct elements are: [1], [2], [2], [3], [1, 2], [2, 2], [2, 3], [1
9 min read
Counting frequencies of array elements
Given an array which may contain duplicates, print all elements and their frequencies. Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}Output : 10 3 20 4 5 1Input : arr[] = {10, 20, 20}Output : 10 1 20 2 A simple solution is to run two loops. For every item count number of times, it occurs.
15+ min read
Count subarrays having a single distinct element that can be obtained from a given array
Given an array arr[] of size N, the task is to count the number of subarrays consisting of a single distinct element that can be obtained from a given array. Examples: Input: N = 4, arr[] = { 2, 2, 2, 2 }Output: 7Explanation: All such subarrays {{2}, {2}, {2}, {2}, {2, 2}, {2, 2, 2}, {2, 2, 2, 2}}.
5 min read