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,

  • MEX([2,2,1])=0\text{MEX}([2,2,1]) = 0 because 00 is not in the array.
  • MEX([3,1,0,1])=2\text{MEX}([3,1,0,1]) = 2 because 00 and 11 are in the array but 22 is not.
  • MEX([0,3,1,2])=4\text{MEX}([0,3,1,2]) = 4 because 00, 11, 22, and 33 are in the array but 44 is not.

You are given an array aa of size nn of nonnegative integers.

For all kk (0kn0 \leq k \leq n), count the number of possible values of MEX(a)\text{MEX}(a) after removing exactly kk values from aa.

Input

The first line contains an integer tt (1t1041 \leq t \leq 10^4) — the number of test cases.

The first line of each test case contains one integer nn (1n21051 \leq n \leq 2 \cdot 10^5) — the size of the array aa.

The second line of each test case contains nn integers, a1,a2,,ana_1, a_2, \ldots, a_n (0ain0 \leq a_i \leq n).

It is guaranteed that the sum of nn over all test cases does not exceed 21052 \cdot 10^5.

Output

For each test case, output a single line containing n+1n+1 integers — the number of possible values of MEX(a)\text{MEX}(a) after removing exactly kk values, for k=0,1,,nk = 0, 1, \ldots, n.

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 MEX=k\text{MEX} = k, it must satisfy two conditions:

  1. All values from 00 to k1k-1 must be present in the array
  2. The value kk must NOT be present in the array

Algorithm Overview

  1. Count Available Elements: First, count how many times each value appears in the original array.

  2. Calculate Required Elements: For each possible MEX value mm:

    • We need at least one occurrence of each value from 00 to m1m-1
    • We must avoid adding any occurrence of value mm
  3. Find Valid Ranges: For each MEX value mm, determine the range of elements we can add while maintaining MEX=m\text{MEX} = m.

  4. Use Difference Array: We use a difference array to efficiently track which positions can achieve each MEX value.

  5. Prefix Sum: Finally, compute the prefix sum of the difference array to get the final counts for each MEX value.

Time Complexity

  • Time: O(n)O(n)
  • Space: O(n)O(n)

submission link