Count pair of indices in Array having equal Prefix-MEX and Suffix-MEX
Given an array arr[] of N elements, the task is to find the number of pairs of indices such that the Prefix-MEX of the one index is equal to the Suffix-MEX of the other index. Order of indices in pair matters.
MEX of an array refers to the smallest missing non-negative integer of the array. For the given problems (i, j) and (j, i) are considered different pairs.
Examples:
Input: A[] = {1, 0, 2, 0, 1}
Output: 11
Explanation: In array A, Prefix-MEX for each element are as {0, 2, 3, 3, 3}, similarly, Suffix-MEX for each element are {3, 3, 3, 2, 0} and all possible pairs of indexes such that prefix-MEX of one is equal to Suffix-MEX of other are (1-based indexing):
(1, 5): prefix of 1 is equal to the suffix of 5
(2, 4): prefix of 2 is equal to the suffix of 4
(3, 3): prefix of 3 is equal to the suffix of 3
(3, 2): prefix of 3 is equal to the suffix of 2
(3, 1): prefix of 3 is equal to the suffix of 1
(4, 3): prefix of 4 is equal to the suffix of 3
(4, 2): prefix of 4 is equal to the suffix of 2
(4, 1): prefix of 4 is equal to the suffix of 1
(5, 3): prefix of 5 is equal to the suffix of 3
(5, 2): prefix of 5 is equal to the suffix of 2
(5, 1): prefix of 5 is equal to the suffix of 1
Input: A[] = {1, 2, 3}
Output: 9
Naive Approach:
The most straightforward way will be to find each element’s Prefix–MEX and suffix–MEX and count a total number of possible pairs and increase the count. And for each element, we have to traverse the complete array again and again therefore complexity will be of order N2.
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Efficient Approach: In this approach, we will pre-compute and store Prefix-MEX and Suffix-MEX for each element.
Follow the steps below to calculate the Prefix-MEX array for the given array:
- Find the maximum element in the given array arr.
- Create a set of integers and store the numbers from 0 to the max element in the set.
- Traverse through the array from i = 0 to N-1:
- For each element, erase that element from the set.
- Now find the smallest element remaining in the set.
- Store the value of this smallest element remaining in the set in the resultant array.
- Return the resultant array as the required answer.
Follow the steps below to implement the idea:
- Create a variable count and initialize it to 0 to store the number of indexes.
- Calculate a Prefix-MEX for arr as P for a given array.
- Reverse the given array arr and calculate the Prefix-MEX array for this revered array as S and reverse S.
- Create a map mp to count the frequency of each element in P.
- Traverse through P increment frequency of current element.
- Traverse through S and check if the current element exists in mp.
- if the current element does not exist in mp then continue.
- else add the frequency of the current element in the variable count.
- print the value of count as a required result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > Prefix_MEX(vector< int >& A, int n)
{
int mx_element = *max_element(A.begin(), A.end());
set< int > s;
vector< int > B(n);
for ( int i = 0; i <= mx_element + 1; i++) {
s.insert(i);
}
for ( int i = 0; i < n; i++) {
auto it = s.find(A[i]);
if (it != s.end())
s.erase(it);
B[i] = *s.begin();
}
return B;
}
void countPairs(vector< int >& arr, int N)
{
int count = 0;
vector< int > P = Prefix_MEX(arr, N);
reverse(arr.begin(), arr.end());
vector< int > S = Prefix_MEX(arr, N);
reverse(S.begin(), S.end());
map< int , int > mp;
for ( int i = 0; i < N; i++) {
mp[P[i]]++;
}
for ( int i = 0; i < N; i++) {
if (mp.find(S[i]) == mp.end()) {
continue ;
}
else {
count += mp[S[i]];
}
}
cout << count << endl;
}
int main()
{
vector< int > arr = { 1, 0, 2, 0, 1 };
int N = arr.size();
countPairs(arr, N);
arr = { 1, 2, 3 };
N = arr.size();
countPairs(arr, N);
return 0;
}
|
Java
import java.util.*;
public class Main {
static List<Integer> prefixMex(List<Integer> A) {
int mxElement = Collections.max(A);
Set<Integer> s = new HashSet<>();
for ( int i = 0 ; i < mxElement + 2 ; i++) {
s.add(i);
}
List<Integer> B = new ArrayList<>(Collections.nCopies(A.size(), 0 ));
for ( int i = 0 ; i < A.size(); i++) {
s.remove(A.get(i));
B.set(i, Collections.min(s));
}
return B;
}
static int countPairs(List<Integer> arr) {
int n = arr.size();
List<Integer> P = prefixMex(arr);
List<Integer> S = new ArrayList<>(arr);
Collections.reverse(S);
S = prefixMex(S);
Collections.reverse(S);
Map<Integer, Integer> mp = new HashMap<>();
for ( int p : P) {
mp.put(p, mp.getOrDefault(p, 0 ) + 1 );
}
int count = 0 ;
for ( int s : S) {
count += mp.getOrDefault(s, 0 );
}
return count;
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList( 1 , 0 , 2 , 0 , 1 );
System.out.println(countPairs(arr));
arr = Arrays.asList( 1 , 2 , 3 );
System.out.println(countPairs(arr));
}
}
|
Python3
from typing import List , Tuple
def prefix_mex(A: List [ int ]) - > List [ int ]:
mx_element = max (A)
s = set ( range (mx_element + 2 ))
B = [ 0 ] * len (A)
for i, a in enumerate (A):
s.discard(a)
B[i] = min (s)
return B
def count_pairs(arr: List [ int ]) - > int :
n = len (arr)
P = prefix_mex(arr)
S = prefix_mex(arr[:: - 1 ])[:: - 1 ]
mp = {}
for p in P:
mp[p] = mp.get(p, 0 ) + 1
count = 0
for s in S:
count + = mp.get(s, 0 )
return count
arr = [ 1 , 0 , 2 , 0 , 1 ]
print (count_pairs(arr))
arr = [ 1 , 2 , 3 ]
print (count_pairs(arr))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
static List< int > Prefix_MEX(List< int > A, int n)
{
int mxElement = A.Max();
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < mxElement + 2; i++) {
s.Add(i);
}
List< int > B = new List< int >( new int [A.Count]);
for ( int i = 0; i < n; i++) {
s.Remove(A[i]);
B[i] = s.Min();
}
return B;
}
static int CountPairs(List< int > arr, int n)
{
List< int > P = Prefix_MEX(arr, n);
List< int > S = new List< int >(arr);
S.Reverse();
S = Prefix_MEX(S, n);
S.Reverse();
Dictionary< int , int > mp
= new Dictionary< int , int >();
foreach ( int p in P) {
if (mp.ContainsKey(p)) {
mp[p]++;
}
else {
mp[p] = 1;
}
}
int count = 0;
foreach ( int s in S) {
if (mp.ContainsKey(s)) {
count += mp[s];
}
}
return count;
}
public static void Main( string [] args)
{
List< int > arr = new List< int >{ 1, 0, 2, 0, 1 };
int N = arr.Count;
Console.WriteLine(CountPairs(arr, N));
arr = new List< int >{ 1, 2, 3 };
N = arr.Count;
Console.WriteLine(CountPairs(arr, N));
}
}
|
Javascript
function Prefix_MEX(A, n)
{
let mx_element = Number.MIN_SAFE_INTEGER;
for (let i=0; i<A.length; i++)
mx_element=Math.max(mx_element, A[i]);
let s= new Set();
let B= new Array(n);
for (let i = 0; i <= mx_element + 1; i++) {
s.add(i);
}
for (let i = 0; i < n; i++) {
if (s.has(A[i]))
s. delete (A[i]);
const [first]=s;
B[i] = first;
}
return B;
}
function countPairs(arr, N)
{
let count = 0;
let P = Prefix_MEX(arr, N);
arr.reverse();
let S = Prefix_MEX(arr, N);
S.reverse();
let mp= new Map();
for (let i = 0; i < N; i++) {
if (mp.has(P[i]))
mp.set(P[i], mp.get(P[i])+1);
else
mp.set(P[i],1);
}
for (let i = 0; i < N; i++) {
if (!mp.has(S[i])) {
continue ;
}
else {
count += mp.get(S[i]);
}
}
console.log(count);
}
let arr = [ 1, 0, 2, 0, 1 ];
let N = arr.length;
countPairs(arr, N);
arr = [ 1, 2, 3 ];
N = arr.length;
countPairs(arr, N);
|
Time Complexity: O(N * log N), log N for inserting and deleting elements from the set, and O(N) for traversing the array.
Auxiliary Space: O(N) for storing Prefix-MEX array.
Related Articles:
Last Updated :
27 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...