MEX Subarray Count in C++Last Updated : 10 May 2025 In this article, we will discuss the MEX Subarray Count in C++ with its example and benefits. When given an array of size N, every element falls inside the range [0, N-1], meaning that the array is a permutation. Finding the number of subarrays whose MEX is more than the median is the current task. The smallest whole number that is absent from the array is MEX, it should be noted. Examples:Input: N=4, arr=[0, 2, 1, 3] Output: 4 Explanation: The subarrays whose MEX is greater than the Median are [0], [0, 2], [0, 2, 1], and [0, 2, 1, 3]. Input: N=4, arr=[1, 0] Output: 2 Explanation: The subarrays with MEX greater than Median are [0], [1, 0]. MEX Subarray Count using Two Pointers:First, we can observe that the MEX of each subarray will be between 0 and N. to calculate the answer for a MEX fixed value. For a fixed value of MEX, let l be the index of the number that is farthest to the left, 0, 1, 2,... mex-1, and let r be the index of the number that is farthest to the right, 0, 1, 2,... mex-1. Let curr, or curr=(r-l)+1, be the current length of the subarray. The number of subarrays can be found using a variety of techniques if the curr is less than or equal to 2*MEX. The MED of the subarray in this instance will be arr[l..r] and fall between [0..MEX-1. Curr's greater than 2*MEX indicates a higher MED for the subarray. Follow the steps to solve the problem:
Example:Below is the implementation of the above approach: Output: ![]() Complexity Analysis: Time Complexity: O(N) Auxiliary Space: O(N) Benefits of MEX Subarray Count in C++The Minimum Excluded Element is commonly called "MEX" in a set or array. When we discuss the "MEX Subarray Count", we may be referring to determining how many subarrays in a particular array have a minimum excluded element. But in the absence of further information or a particular problem statement, allow us to list some possible advantages of handling MEX subarray count-related issues:
Recall that the advantages vary depending on the situation and issue. Practicing MEX subarray count problems is one technique to develop your comprehension of algorithmic principles in the context of arrays and sets. Each problem advances our general programming and problem-solving abilities. Next TopicAssign-cookies-in-cpp |
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India
