Count pair of indices in Array having equal Prefix-MEX and Suffix-MEX
Last Updated :
23 Jul, 2025
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++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the prefix MEX
// for each array element taking vector
// and its size as parameter
vector<int> Prefix_MEX(vector<int>& A, int n)
{
// Maximum element in vector A
int mx_element = *max_element(A.begin(), A.end());
// Set to store all elements for
// 0 to mx_element
set<int> s;
// Vector to store Prefix-MEX for
// given input array
vector<int> B(n);
// Store all number from 0
// to maximum element + 1 in a set
for (int i = 0; i <= mx_element + 1; i++) {
// inserting elements in set
s.insert(i);
}
// Loop to calculate MEX for each
// index in the array
for (int i = 0; i < n; i++) {
// Checking if A[i] is present
// in set
auto it = s.find(A[i]);
// If present then we erase
// that element
if (it != s.end())
s.erase(it);
// Store the first element of set
// in vector B as Mex of
// prefix vector
//cout<<*s.begin()<<" ";
B[i] = *s.begin();
}
// Return the vector B
return B;
}
void countPairs(vector<int>& arr, int N)
{
// Count variable to store number of
// indices whose prefix-mex and
// suffix-mex are equal
int count = 0;
// Vector P stores the Prefix-MEX
// for given array
vector<int> P = Prefix_MEX(arr, N);
// Reversing given array
reverse(arr.begin(), arr.end());
// vector S stores the reverse of
// Suffix-MEX for given array
vector<int> S = Prefix_MEX(arr, N);
// Reversing vector S will give
// suffix-MEX for given array
reverse(S.begin(), S.end());
// map to count frequency of each
// element in arr1
map<int, int> mp;
// Counting frequency of each
// element of arr1
for (int i = 0; i < N; i++) {
mp[P[i]]++;
}
// Traversal through arr S
for (int i = 0; i < N; i++) {
// Check if element does not exist
// in map
if (mp.find(S[i]) == mp.end()) {
continue;
}
// if exist add it's frequency
// to count
else {
count += mp[S[i]];
}
}
cout << count << endl;
}
// Driver code
int main()
{
vector<int> arr = { 1, 0, 2, 0, 1 };
int N = arr.size();
// Function Call
countPairs(arr, N);
arr = { 1, 2, 3 };
N = arr.size();
// Function Call
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#
// C# code to implement the approach
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
// Function to find the prefix MEX
// for each array element taking vector
// and its size as parameter
static List<int> Prefix_MEX(List<int> A, int n)
{
// Maximum element in List A
int mxElement = A.Max();
// Set to store all elements for
// 0 to mx_element
HashSet<int> s = new HashSet<int>();
// Store all number from 0
// to maximum element + 1 in a set
for (int i = 0; i < mxElement + 2; i++) {
// inserting elements in set
s.Add(i);
}
// List to store Prefix-MEX for
// given input array
List<int> B = new List<int>(new int[A.Count]);
// Loop to calculate MEX for each
// index in the array
for (int i = 0; i < n; i++) {
// Checking if A[i] is present in set
// If present then we remove that element
s.Remove(A[i]);
// Store the first element of set
// in vector B as Mex of
B[i] = s.Min();
}
return B;
}
static int CountPairs(List<int> arr, int n)
{
// Vector P stores the Prefix-MEX
// for given array
List<int> P = Prefix_MEX(arr, n);
// vector S stores the reverse of
// Suffix-MEX for given array
List<int> S = new List<int>(arr);
// Reversing given array
S.Reverse();
S = Prefix_MEX(S, n);
// Reversing vector S will give
// suffix-MEX for given array
S.Reverse();
// map to count frequency of each
// element in arr1
Dictionary<int, int> mp
= new Dictionary<int, int>();
// Counting frequency of each
// element of arr1
foreach(int p in P) {
if (mp.ContainsKey(p)) {
mp[p]++;
}
else {
mp[p] = 1;
}
}
// Count variable to store number of
// indices whose prefix-mex and
// suffix-mex are equal
int count = 0;
// Traversal through arr S
foreach(int s in S) {
if (mp.ContainsKey(s)) {
count += mp[s];
}
}
return count;
}
// Driver code
public static void Main(string[] args)
{
List<int> arr = new List<int>{ 1, 0, 2, 0, 1 };
int N = arr.Count;
// Function Call
Console.WriteLine(CountPairs(arr, N));
arr = new List<int>{ 1, 2, 3 };
N = arr.Count;
// Function Call
Console.WriteLine(CountPairs(arr, N));
}
}
// This Code is Contributed by Prasad Kandekar(prasad264)
JavaScript
// javascript code to implement the approach
// Function to find the prefix MEX
// for each array element taking vector
// and its size as parameter
function Prefix_MEX(A, n)
{
// Maximum element in vector A
let mx_element = Number.MIN_SAFE_INTEGER;
for(let i=0; i<A.length; i++)
mx_element=Math.max(mx_element, A[i]);
// Set to store all elements for
// 0 to mx_element
let s=new Set();
// Vector to store Prefix-MEX for
// given input array
let B=new Array(n);
// Store all number from 0
// to maximum element + 1 in a set
for (let i = 0; i <= mx_element + 1; i++) {
// inserting elements in set
s.add(i);
}
// Loop to calculate MEX for each
// index in the array
for (let i = 0; i < n; i++) {
// Checking if A[i] is present
// in set
//auto it = s.find(A[i]);
// If present then we erase
// that element
if (s.has(A[i]))
s.delete(A[i]);
// Store the first element of set
// in vector B as Mex of
// prefix vector
const [first]=s;
B[i] = first;
}
// Return the vector B
return B;
}
function countPairs(arr, N)
{
// Count variable to store number of
// indices whose prefix-mex and
// suffix-mex are equal
let count = 0;
// Vector P stores the Prefix-MEX
// for given array
let P = Prefix_MEX(arr, N);
// Reversing given array
arr.reverse();
// vector S stores the reverse of
// Suffix-MEX for given array
let S = Prefix_MEX(arr, N);
// Reversing vector S will give
// suffix-MEX for given array
S.reverse();
// map to count frequency of each
// element in arr1
let mp=new Map();
// Counting frequency of each
// element of arr1
for (let i = 0; i < N; i++) {
//mp[P[i]]++;
if(mp.has(P[i]))
mp.set(P[i], mp.get(P[i])+1);
else
mp.set(P[i],1);
}
// Traversal through arr S
for (let i = 0; i < N; i++) {
// Check if element does not exist
// in map
if (!mp.has(S[i])) {
continue;
}
// if exist add it's frequency
// to count
else {
count += mp.get(S[i]);
}
}
console.log(count);
}
// Driver code
let arr = [ 1, 0, 2, 0, 1 ];
let N = arr.length;
// Function Call
countPairs(arr, N);
arr = [ 1, 2, 3 ];
N = arr.length;
// Function Call
countPairs(arr, N);
// This code is contributed by poojaagarwal2.
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:
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem