E. MEX Count
Codeforces Round 1034 (Div. 3) E
Problem Statement
Time limit per test: 3 seconds
Memory limit per test: 256 megabytes
Define the MEX (minimum excluded value) of an array to be the smallest nonnegative integer not present in the array. For example,
- because is not in the array.
- because and are in the array but is not.
- because , , , and are in the array but is not.
You are given an array of size of nonnegative integers.
For all (), count the number of possible values of after removing exactly values from .
Input
The first line contains an integer () — the number of test cases.
The first line of each test case contains one integer () — the size of the array .
The second line of each test case contains integers, ().
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output a single line containing integers — the number of possible values of after removing exactly values, for .
Solution
Key Insight
Instead of thinking about removing elements from the array, we can think about it as adding elements to an initially empty array. This perspective makes the problem much clearer.
Understanding MEX Requirements
For an array to have , it must satisfy two conditions:
- All values from to must be present in the array
- The value must NOT be present in the array
Algorithm Overview
Count Available Elements: First, count how many times each value appears in the original array.
Calculate Required Elements: For each possible MEX value :
- We need at least one occurrence of each value from to
- We must avoid adding any occurrence of value
Find Valid Ranges: For each MEX value , determine the range of elements we can add while maintaining .
Use Difference Array: We use a difference array to efficiently track which positions can achieve each MEX value.
Prefix Sum: Finally, compute the prefix sum of the difference array to get the final counts for each MEX value.
Time Complexity
- Time:
- Space: