We need to determine for a given array a of length n, the earliest step t such that it's impossible to have produced the prefix a[1..t] following the rules. If the entire array is possible, output -1.
Rules: Starting with empty array. At step m (1-indexed), we have previous elements a1..a_{m-1}. We choose a subset (possibly empty) of indices from 1..m-1, i.e., some elements from the array so far (with repetition? It says subset of indices, so each element is used at most once, but it's a multiset? Actually the array is a sequence; we pick indices, so we select some elements (could be duplicate values? Since the array can have duplicate values, picking indices yields a multiset where each occurrence is distinct. But the subset is defined by indices, so no repetition of same index; but if there are duplicates, selecting different indices with same value yields that value multiple times? The mex of a multiset: duplicates don't matter; presence matters. So it's essentially a set of values from the chosen indices. So picking indices yields a set of numbers (ignoring duplicates). So it's fine.
Then we compute mex of that selected set: smallest non-negative integer not present. Then append that mex to the array as a_m.
We need to know whether there exists a sequence of subset choices that yields exactly the given array.
Goal: minimal t where it's impossible.
Observations: The process is reminiscent of constructing any array? But there are constraints.
Let’s reason.
At step m, we can choose any subset of previous elements. The mex of that subset can be any non-negative integer? Not exactly, because mex depends on which numbers are present.
What are the possible values of mex(S) for S subset of current array elements? The current array (prefix) contains some numbers. We can choose any subset of them. The mex of the chosen subset can be any integer that is the smallest missing from that subset. So it can be 0 if we choose a subset that does not contain 0 (including empty set gives mex=0). It can be 1 if we choose a subset that contains 0 but not 1. It can be 2 if we choose subset that contains 0 and 1 but not 2. In general, for any integer x, we can obtain mex = x if we can choose a subset that contains all numbers from 0 to x-1 but does not contain x. Additionally, we might also be able to obtain larger mex if we include all 0..x and omit x+1, etc.
But note: The subset we choose can be arbitrary; we can include or exclude any element. So the condition for being able to produce a value v at step m is: there exists a subset of previous elements such that mex = v. Equivalently, we need to be able to have that all numbers 0..v-1 are present in the subset, and v is not present. But we can also have additional numbers beyond v, that doesn't matter.
So necessary and sufficient: Among the previous elements, we must have at least one occurrence of each number from 0 to v-1 (so that we can include them in the subset). And we must be able to avoid including v: i.e., there must be at least one occurrence of v? Actually, to ensure v is not present, we must be able to choose a subset that does not contain v. Since we can choose any subset, we can simply not pick any index that has value v. So the only requirement is that it is possible to include all numbers 0..v-1. That means that for each i in [0, v-1], there exists at least one occurrence of i in the previous array (a1..a_{m-1}). Because we can pick exactly one index for each such i (or more, but at least one). Since we can choose the subset arbitrarily, we can include one occurrence of each of those numbers (if they exist) and exclude all others. So indeed, v is attainable at step m iff for all i in [0, v-1], i appears at least once in the prefix before m.
But wait: There's also the possibility that v=0: we don't need any numbers; we can always take empty set -> mex=0. So condition is trivially satisfied. So 0 is always possible at any step? Actually, if we need to produce a_m = 0, we can always do that by picking empty subset. So 0 is always allowed. So condition for v>0: all numbers from 0 to v-1 must have appeared at least once before step m.
Is that also sufficient? Let's check: Suppose we have all numbers 0..v-1 present at least once. We want to produce mex = v. Choose subset S = {one occurrence of each of 0,1,...,v-1}. Then S contains all those numbers, and does not contain v (since we didn't include any v). Also we must ensure we don't accidentally include v if we also pick some v? We simply don't. So mex(S)=v indeed. So yes.
Thus the condition: a_m is possible iff either a_m = 0, or all numbers 0..a_m-1 appear somewhere in indices 1..m-1.
Now is that the only condition? Let's test against examples: Example1: [0,1,2,1]. Check step1: a1=0 -> allowed. Step2: a2=1 -> need 0 present? Yes (a1=0) -> allowed. Step3: a3=2 -> need 0,1 present? Yes (0,1) -> allowed. Step4: a4=1 -> need 0 present? Yes -> allowed. So conditions satisfied -> possible. Example2: [1,0,1] -> step1: a1=1 -> need 0 present? But prefix is empty, so 0 not present -> not allowed. So t=1 -> output 1. Example3: [0,1,2,239] -> steps1-3: 0,1,2 okay. Step4: a4=239 -> need all numbers 0..238 present in prefix? They are not; only 0,1,2 present. So not allowed. So t=4. Output 4. Matches.
But is that all? Let's think of any additional constraints: The process allows choosing any subset of previous indices. But does it allow choosing a subset that might contain duplicate values? No matter. The condition seems necessary and sufficient. However, note that the mex of a set is the smallest non-negative integer not present. If we include all numbers 0..v-1, mex = v if v not present. But could it be something else if we also include numbers > v? That's fine. So indeed we can always produce v given those numbers. So the rule is: at step m, a_m must be at most the current mex of the whole set? Not exactly: The mex of the whole set of previous elements might be some M. But we can produce any v <= M? Let's see: If the current set (all previous elements) has all numbers 0..M-1 present at least once, and M is missing. Then for any v < M, we have all numbers 0..v-1 present, so v is possible. For v = M, we need all numbers 0..M-1 present, which is true, and we need to avoid including M; but M is missing from the entire array, so it's automatically not included. So v = M is also possible (choose subset containing all numbers 0..M-1). For v > M, we need some numbers beyond M that are not present (like M itself) to be present? Actually for v > M, we need all numbers 0..v-1 present, which includes M. But M is missing from the array (by definition of mex). So v > M is impossible. So possible values at step m are exactly all v such that v <= M, where M is mex of the entire set of previous elements? Check: If M is mex of the multiset of all previous elements, then numbers 0..M-1 are present at least once, M is missing. Then for any v <= M, the condition holds: if v < M, then 0..v-1 present. If v = M, then 0..M-1 present, and M is missing, so we can avoid it. So indeed the set of possible a_m values is {0,1,...,M}. Also note that M could be 0 if no 0? But at step1, previous set empty, mex = 0? The mex of empty set is 0. So M=0, possible a1 = 0 only. That matches condition: only 0 allowed. So the condition simplifies to: at step m, a_m must be <= current mex of the whole previous array (call it M_{m-1}), where M_{m-1} = mex({a_1,...,a_{m-1}}). Moreover, is it also possible to have a_m equal to something greater than M_{m-1}? Only if the condition holds, but that would require numbers 0..a_m-1 all present, which would mean that M_{m-1} (the smallest missing) is at least a_m, i.e., a_m <= M_{m-1}. So exactly.
Thus the process is equivalent to: Starting with an empty set, at each step we append a number a_m. The condition for it to be possible is: a_m <= mex(previous elements). Because if a_m > mex(previous), then there exists some missing number less than a_m, so that missing number is not present in previous, thus condition fails. Conversely, if a_m <= mex(previous), then all numbers 0..a_m-1 are present (since mex is smallest missing, so numbers less than mex are all present), and a_m might be equal to mex, in which case a_m itself is missing; if a_m < mex, a_m is present? Actually if a_m < mex, then a_m is among the numbers 0..mex-1, so it is present in the previous array? Not necessarily: The condition for producing a_m is only that we can choose subset containing all numbers 0..a_m-1. It doesn't matter if a_m itself is present or not. But if a_m < mex, then a_m is definitely present? Since all numbers less than mex are present at least once (by definition of mex). So a_m is present. That's fine; we can still produce a_m = some value less than mex by selecting subset containing 0..a_m-1 (which includes a_m? No, a_m-1 is less than a_m, so the set includes numbers up to a_m-1, not a_m itself). So we don't need to include a_m. So it's okay even if a_m is present. So condition a_m <= mex(previous) is necessary and sufficient.
But wait: Consider scenario where previous elements contain all numbers 0..k-1, but are missing some number j < a_m? Actually if a_m <= mex(previous), then by definition mex(previous) is the smallest missing number, so all numbers 0..mex(previous)-1 are present, thus all numbers 0..a_m-1 are present because a_m-1 <= mex(previous)-1. So condition holds. If a_m > mex(previous), then mex(previous) is a number missing from previous, and since mex(previous) < a_m, the condition fails because we need mex(previous) present to cover 0..a_m-1. So yes.
Thus the process is exactly: a_1 must be 0 because mex(empty)=0? Actually mex(empty)=0, so condition a_1 <= 0 => a_1=0. So first element must be 0. That matches example2.
After adding a_m, the mex of the new set may change. The mex updates based on the new element.
So the entire array is feasible iff for every m, a_m <= mex of previous prefix (call it M_{m-1}), with M_0 = 0. And we can then compute M_m = mex(prefix up to m). So it's an easy check.
But we also need to output the earliest step t where condition fails, i.e., where a_t > M_{t-1}. If never fails, -1.
Given n up to 100k, a_i up to 1e9. So we can simulate maintaining the mex.
But careful: M_{m} is mex of all a_1..a_m. To compute it efficiently, we need to update as we add a new number. Since numbers can be up to 1e9, we cannot keep a full boolean array. But we only need to know the smallest non-negative integer not present. As we progress, the mex can increase but also possibly decrease? Can mex decrease? Adding a new element can only add a number, so the set of present numbers grows. mex is the smallest missing number. Adding a number might fill a gap, causing mex to increase. It cannot decrease because adding numbers can only fill missing numbers, not create new gaps. Actually, if we add a number that is larger than current mex, the mex stays the same because the missing smallest remains. If we add a number that is less than current mex, it might fill a gap? But if it's less than mex, it is already present? Not necessarily: If the current set contains all numbers from 0 to mex-1, but may have some numbers missing among those? Actually by definition, mex is smallest missing. So all numbers 0..mex-1 are present. So any number less than mex is already present. Adding it again does nothing. So mex cannot decrease; it can stay the same or increase (if we add exactly the current mex). So mex is non-decreasing.
Thus M_{m} is monotonic non-decreasing.
We can simulate: maintain a count of numbers seen. Since we only need the mex, we can maintain a set of numbers present, but more efficiently, we can keep a frequency map for numbers that are <= current candidate mex, and update.
A standard approach: maintain a frequency array for numbers up to n+something? But a_i can be large. However, note that the mex can never exceed n+1? Actually, consider we can add numbers up to 1e9. But mex is the smallest missing integer. At step m, we have at most m distinct numbers? Not exactly, there can be repeats. The mex could be large if we have all numbers from 0 to K-1 present, and K is not present. Since we have at most m elements, we cannot have all numbers from 0 to K-1 present if K > m? Actually we could: For example, if we have numbers 0,1,2,...,m-1, then mex = m. So mex can be as large as m (since we have m elements, we could have all numbers 0..m-1 distinct). So mex ≤ m+1? Let's see: At step m, the maximum possible mex is m+1? Consider we have m elements; could we have all numbers from 0 to m? That would require m+1 distinct numbers, impossible. So mex is at most m (since we can have all 0..m-1 present, then mex = m). So mex ≤ m. Indeed, the mex cannot exceed the number of elements + 1? Actually if we have m elements, the maximum mex is m+1? Wait: mex is smallest missing integer. If we have m elements, the set of numbers could be {0,1,2,...,m-1} (m distinct numbers), then mex = m. So mex = m. To have mex = m+1, we would need all numbers from 0 to m present, which is m+1 numbers, impossible with only m elements. So mex ≤ m. More generally, mex ≤ number of distinct elements among 0..something. But since there are at most m elements, mex ≤ m. So mex is at most n (when m=n). So we only need to track numbers in range 0..n, because numbers larger than n are irrelevant for mex (they won't affect the smallest missing integer less than or equal to n). However, when we add a number > n, it does not affect mex because it's > current mex? It could affect mex if it's smaller than mex? But mex ≤ m ≤ n, so if we add a number > n, it's definitely ≥ n+1, which is > mex (since mex ≤ m ≤ n). So adding such a number does not change mex (since mex is ≤ n). So we can safely ignore numbers > n for the purpose of mex computation. But note: The condition for feasibility: a_m <= M_{m-1}. M_{m-1} ≤ m-1 ≤ n. So if a_m > n, then it's definitely > M_{m-1} (since M_{m-1} ≤ m-1 ≤ n), thus it's impossible. So we can quickly detect impossibilities for large a_i. But we still need to compute mex accurately.
So we can simulate: keep a boolean or frequency array for numbers 0..n (maybe up to n+1). Actually since mex can go up to n, we need to track numbers 0..n inclusive? Actually to compute mex we need to know which numbers 0..n are present. Since mex ≤ n, we can keep an array present[0..n] (or maybe up to n, because if all 0..n are present, mex would be n+1, but that's impossible with n elements? Let's check: At step n, we have n elements. Could they be all numbers 0..n? That would be n+1 numbers, impossible. However, if we have duplicates, we could have some numbers missing but still have numbers up to n present? Actually to have mex = n+1, we need all numbers 0..n present. That would require at least n+1 distinct numbers. With n elements, impossible. So mex never reaches n+1. So we only need to track numbers 0..n-1? But consider n=1: we have one element, mex could be 1? If a1=0, then mex after step1 is 1. So mex =1 = n. So we need to consider numbers up to n. But is it possible mex = n? For m=n, if we have all numbers 0..n-1 present, then mex = n. So we need to track numbers 0..n-1 to determine mex; if all 0..n-1 are present, mex = n. So we need to know about numbers 0..n-1. For numbers equal to n, they may appear, but that's > mex? Actually mex could be less than n even if n appears. But tracking n is not necessary for mex because mex will be ≤ n. However, if n appears, it doesn't affect mex (since mex is the smallest missing, and if all smaller numbers are present, mex could be less than n if some smaller number missing). But to detect when mex becomes n, we need to know if all numbers 0..n-1 are present. So we need to track presence of numbers 0..n-1. That's enough. But we also need to track numbers exactly equal to n? Not needed for mex. However, condition a_m <= M_{m-1} might involve a_m = n? If M_{m-1} can be n? At step m-1, M could be up to m-1. For m = n+1? Actually m ranges 1..n. So the maximum M_{m-1} is at most m-1 <= n-1 when m=n. So M_{n-1} <= n-1. So at step n, M_{n-1} <= n-1. So a_n could be at most n-1? Actually if M_{n-1}=n-1, then a_n <= n-1. But could M_{n-1} be n? No, because with n-1 elements, mex ≤ n-1. So a_n cannot be n. So a_n > n-1 always impossible? Let's test: Could we have a_n = n? For n=1, a1 must be 0, so no. For n=2, could we have array [0,2]? Check: step2: previous mex = 1, so a2 must <=1 -> 2 is impossible. So indeed a_n cannot be n. So numbers > n-1 are impossible anyway. But what about earlier steps? For m small, M_{m-1} is small. So any a_m > m-1 likely impossible? Not exactly: e.g., step3 could have a3=2, while m-1=2, so allowed. So a_m can be equal to m-1 at most. In general, a_m <= m-1? Let's check: M_{m-1} ≤ m-1. So indeed a_m ≤ m-1. So any a_m ≥ m is automatically invalid. That's a quick check.
But careful: Could M_{m-1} be exactly m-1? Possibly if we have all numbers 0..m-2 present. So a_m can be up to m-1. So the maximum valid value at step m is m-1. That's a simple necessary condition: a_m < m. Because a_m <= m-1. So if a_m >= m, it's impossible. So for m=1: a1 must be 0 (since <1). Good.
However, is that condition also sufficient? Not exactly: Even if a_m < m, it could still be that M_{m-1} is less than a_m, e.g., if we haven't yet seen some numbers less than a_m. For instance, m=3, a3=1, but if we have previous array [0,0], then M_{2}=? set contains 0, so mex=1. So a3=1 <=1, allowed. But if previous array [2,0]? But step2: a2=2? But that would have been invalid earlier because a2=2 > M_1? M_1 after a1? But let's consider a prefix that is valid so far: For m=3, a1=0 (must). Then a2 must be ≤ M_1=1. So a2 can be 0 or 1. So we cannot have a2=2. So in any valid prefix, the condition a_i < i holds, but also stronger condition that M_{i-1} ≥ a_i. So we need to compute M.
Given that M_{m-1} is the mex of prefix of length m-1. Since mex is monotonic non-decreasing, we can compute it incrementally.
We need to compute for each m from 1 to n: check if a_m <= M_{m-1}. If not, output m. If all pass, output -1.
Now compute M_{m}. Initially M0 = 0. For each new a_m (if added), update M. Since a_m may be less than current M or equal to M? Let's define current mex = M. We'll maintain a frequency count of numbers from 0 up to maybe current M+? Actually after adding a_m, if a_m == M, then we need to increase M to the next missing number. If a_m < M, it doesn't affect M because that number is already present. If a_m > M, it's irrelevant (but such a_m would have been invalid anyway since we only add if a_m <= M). So in valid steps, a_m is either less than M (no change) or equal to M (then M increases). So M is exactly the number of times we have successfully added the current mex. This is similar to building a sequence where we can only add numbers not exceeding current mex, and when we add the current mex, the mex increments to the next missing number.
But careful: After adding a_m = M, the mex becomes the smallest integer > M that is missing. However, since we had all numbers 0..M-1 present, now we also have M present, so we have all numbers 0..M present. So the new mex is the smallest integer > M not present. It could be M+1 if M+1 is not present. But we may have already some numbers > M present that could fill gaps? Actually numbers > M don't affect the mex if M+1 is missing. However, if M+1 is present (maybe from earlier steps? But earlier steps can't have M+1 because M was the mex before, so M was missing, but numbers > M could have been present. Could we have M+1 present before? Yes, we could have numbers > M present even though M is missing. Example: After step 2: a1=0, a2=2? But a2=2 would be invalid because M1=1, 2>1. So in a valid sequence, before step m, all numbers less than M are present, but numbers greater than M may appear. Could M+1 be present? Possibly, if we added a number > M earlier? But earlier steps had to be valid, meaning at step when we added that number, say value v > current mex at that time? Let's examine: Suppose at some step when current mex was M', we added a value v > M'. That would be invalid because condition requires v <= M'. So we can never add a number larger than the current mex at that step. Therefore, at any point, all numbers that have been added are ≤ current mex at the time of addition. Since mex is non-decreasing, numbers added are at most the mex at that time, which is ≤ the current mex later? Actually, consider: At step i, we added a_i ≤ M_{i-1}. Then after addition, M_i may increase, but never exceeds M_{i-1}+1 (if a_i = M_{i-1}). So a_i is at most M_{i-1} which is ≤ eventual mex? Not necessarily. But crucially, a_i is always ≤ M_{i-1} ≤ final mex? Not exactly. But we can prove by induction that at any point, all numbers in the set are ≤ the current mex? Let's test: Initially empty, mex=0, trivially. After step, if we add a_i = M_{i-1}, then new mex becomes some value ≥ M_{i-1}+1. So a_i = old mex, which is less than new mex. If we add a_i < M_{i-1}, then it is less than old mex, and old mex remains, so still ≤ mex. So indeed, after each valid step, every element in the array is ≤ current mex. Because if a_i ≤ old mex ≤ new mex (since mex never decreases). So all elements are ≤ mex. That means numbers > mex cannot appear. Thus M+1 cannot be present because it would be > mex. So in a valid sequence, the set consists of numbers ≤ mex, and includes all numbers from 0 to mex-1. Therefore, after adding mex, we now have all numbers 0..mex, so new mex becomes mex+1 (since mex+1 was not present before, and still not present because all numbers ≤ old mex were ≤ old mex, and any number > old mex is > old mex, but could some number = old mex+1 have been added earlier? That would be > old mex, violating the condition at that time because it would have been > mex at that earlier time. So it can't. So indeed, after adding the current mex, the mex increases by exactly 1. So the process is even simpler: In a valid sequence, a_i must be ≤ current mex (which is the number of distinct integers from 0 upward that have been achieved). Moreover, when a_i equals current mex, mex increments by 1. So mex essentially counts how many times we have "filled" the next integer in order.
Thus we can simulate: Let mex = 0 initially. For i from 1 to n:
- if a_i > mex: invalid -> answer i.
- else (a_i <= mex):
- if a_i == mex: mex = mex+1 (then while we have? Actually after increment, maybe the new mex is still present? But we need to check if mex+1 is already present? But as argued, it cannot be present because all numbers are ≤ old mex. So new mex = mex+1 automatically. However, consider scenario where we had some numbers > old mex? They cannot appear. So yes, new mex = old mex+1.
- else (a_i < mex): no change.
But wait: Is it possible that after adding a_i < mex, the mex could increase because we might have filled some gap? For mex to increase, we need the current mex to be present. The current mex is the smallest missing number. Adding a number less than mex does not fill that missing number; it might fill a gap later? But mex is the smallest missing, so any missing number less than mex doesn't exist. So adding any number less than mex is already present? Not necessarily: Could there be a missing number less than mex? No, by definition mex is the smallest missing, so all numbers < mex are present. So any number less than mex is already present. Adding it again doesn't change presence. So mex remains unchanged. So indeed.
Thus the simulation is correct.
But careful: The argument that all numbers ≤ current mex holds only if the sequence has been valid so far. So we can rely on it while checking step by step: if we encounter a_i > mex, it's invalid. If a_i <= mex, we can safely update mex if a_i == mex. And after that, we maintain the invariant that all numbers in the prefix are ≤ mex and all numbers 0..mex-1 are present. We need to ensure that after incrementing mex to mex+1, indeed all numbers 0..mex are present? We added mex, so yes. And all numbers previously are ≤ old mex, which is ≤ new mex, and none are equal to new mex because they were ≤ old mex. So invariant holds.
Thus the problem reduces to simple linear scan with O(n) time and O(1) extra memory? Not exactly, because we need to know that after incrementing mex, there aren't other numbers that could cause the mex to jump further? But as argued, because we maintain that all numbers in the prefix are ≤ current mex, and we just added the current mex, now the new smallest missing is the next integer after the current mex. Since all numbers are ≤ old mex, they cannot be equal to new mex. So mex becomes exactly old mex+1. No need to check further.
But wait: Consider a scenario where we have numbers: 0,2? But 2 cannot appear because at step2, mex after step1 is 1, so a2 must be ≤1. So 2 invalid. So indeed, no such case.
Thus the algorithm is simple:
Initialize mex = 0.
For i from 1 to n:
read a_i
if a_i > mex:
output i and exit
else if a_i == mex:
mex = mex + 1
else: // a_i < mex, do nothing
Continue.
If finish loop, output -1.
Check with examples:
Ex1: start mex=0
i1 a1=0 -> a1==mex? yes -> mex=1
i2 a2=1 -> a2==1? yes -> mex=2
i3 a3=2 -> mex=2? yes -> mex=3
i4 a4=1 -> a4 <= mex? 1 <=3 -> a4!=mex -> no change.
Finish -> -1.
Ex2: mex=0
i1 a1=1 -> 1>0 -> output 1.
Ex3: mex=0
i1 a1=0 -> mex=1
i2 a2=1 -> mex=2
i3 a3=2 -> mex=3
i4 a4=239 -> 239 >3 -> output 4.
Matches.
But is there any subtlety? Let's test more cases. What about array [0,0,1]?
Step1: mex=0, a1=0 -> mex=1
Step2: mex=1, a2=0 -> 0<=1, !=mex -> mex stays 1
Step3: mex=1, a3=1 -> a3==mex -> mex=2. Valid. Could this be produced? Let's see: Starting empty. Step1: empty subset -> 0. Step2: we have [0]. To get 0 again, we need subset with mex=0: choose subset that doesn't contain 0, e.g., empty subset -> 0. So possible. Step3: have [0,0]. Need to get 1: choose subset containing 0? Actually need 0 present to get mex=1. We have 0's, can choose a subset with 0 (any) and not 1. So mex=1. So valid. So algorithm says valid. Good.
What about [0,1,0,2]?
Step1:0->mex=1
Step2:1->mex=2
Step3:0 -> 0<=2, !=2, mex stays 2
Step4:2 -> a4 == mex? yes -> mex=3. Valid. Is it possible? Let's try: steps: [0], [0,1], [0,1,0], now we need 2. Previous mex after step3 is? Set contains 0,1; mex=2. So we need to produce 2. We can choose subset containing 0 and 1? Yes, we have both. So possible. So valid.
What about [0,2,1]? Step1:0->mex=1; step2:a2=2>1 -> invalid step2. So output 2. Indeed impossible.
Edge: n=100000, values large. Works.
But is there any scenario where a_i <= mex but still impossible because of some more complex condition? Let's think deeper: The subset selection allows us to pick any subset of previous elements. Our derived condition is that a_m is possible iff a_m <= mex(previous). We argued sufficiency by constructing subset containing exactly one occurrence of each number from 0 to a_m-1. But we must ensure that for each number i in 0..a_m-1, there is at least one occurrence in the previous array. Since mex(previous) = M, we know that all numbers 0..M-1 are present. If a_m <= M, then a_m-1 <= M-1, so all numbers 0..a_m-1 are present. So we can indeed pick one occurrence each. But is it always possible to pick a single occurrence of each number without picking any extra that might cause issues? We can just pick the indices that correspond to the first occurrence of each number, or any. So yes, it's possible. So sufficiency holds.
Thus the condition is exactly a_m <= mex(previous). So algorithm stands.
Now we need to output minimal t where mistake occurs. That's the first i where a_i > mex_{i-1}. Since we stop at first mistake, we can output i.
But wait: Could there be a scenario where the process could have been consistent even if a_i > mex_{i-1} because maybe we could have chosen different subsets earlier leading to a different prefix that would allow it? The problem asks: given the final array, we need to determine if there exists some sequence of subset choices that yields exactly that array. So if we find that with the given array, at step i the condition a_i > mex(prefix[1..i-1]) holds, then it's impossible to have produced that prefix, regardless of earlier choices? But wait, our derivation of condition used the actual prefix values a_1..a_{i-1}. However, the process might allow earlier choices that affect the set of numbers available at step i, but the prefix a_1..a_{i-1} is fixed. So the set of numbers available at step i is exactly the multiset of those values. So the mex of that set is determined. There's no freedom: the prefix is given. So if a_i > mex(prefix[1..i-1]), then it's impossible to have chosen any subset at step i that yields a_i, because the condition for possibility is solely based on the existing numbers. So indeed mistake must have occurred at or before step i. But could it be that the mistake occurred earlier, and we are only detecting it at step i? The problem asks: minimum step t such that he definitely made a mistake on at least one of the steps 1..t. If we detect impossibility at step i, it means that given the outcomes of steps 1..i-1 (which are as in the array), there is no way to have produced a_i. That implies that there must be a mistake among steps 1..i. But could the mistake have been earlier, i.e., step j < i, and still step i might be reachable if earlier steps were different? But since we are given the actual outcomes, we are checking consistency. If step i is inconsistent with the prefix, it doesn't tell us which step was wrong, just that at least one step in 1..i is wrong. The minimal t is the first i where inconsistency appears (since for all earlier steps j < i, the prefix up to j is self-consistent). Because if the prefix up to i-1 is self-consistent (i.e., there exists a sequence of choices that yields exactly that prefix), then step i would be the first mistake. But is it guaranteed that if prefix up to i-1 satisfies the condition for all j <= i-1, then there exists a sequence of choices that yields that prefix? We need to verify that the condition a_j <= mex(prefix[1..j-1]) for all j <= i-1 is not only necessary but also sufficient for the existence of some choice history that yields that exact prefix. In other words, given any sequence a_1..a_{k} satisfying a_1=0? Actually a_1 must be 0 because mex(empty)=0, so condition gives a_1 <=0 => a_1=0. And for j>1, a_j <= mex(previous). Does this guarantee that there is a way to pick subsets at each step to produce exactly those a_j? We argued that at each step individually, given the previous elements, there exists a subset that yields the desired a_j (by picking one of each of 0..a_j-1). However, we must also ensure that the choices can be made sequentially without conflict? The subset choice at each step does not affect the future values except by determining the new element appended. Since the existence of a subset for step j depends only on the multiset of previous elements, not on how we chose previous subsets. So if at each step the condition holds, we can independently choose a suitable subset for that step, and the resulting appended element will be as desired. There's no interdependence that would prevent us from using the same element indices for different steps? Actually, subsets are chosen independently each step; they don't affect the array beyond appending the new element. The array is fixed; we don't need to specify which indices we used; we just need to know that there exists some choice at step j that yields a_j, given the array so far. Since the array so far is exactly the prefix we have, and we are free to choose any subset of indices from that prefix, there is no constraint linking choices across steps (like "we must have used some specific indices" that might be needed later). Because later steps only care about the set of values present, not which indices were used earlier. So as long as each step individually is feasible given the current multiset, we can realize the whole sequence by making appropriate choices at each step. Therefore, the condition is sufficient.
Thus the minimal t is indeed the first i where condition fails. Because for i-1, if condition holds, the prefix is realizable, so mistake hasn't necessarily occurred earlier; it's possible that the process was correct up to i-1, and the mistake is at step i (or possibly earlier but that would contradict the realizability of prefix). But could there be a scenario where condition holds for all steps up to i, but still the whole prefix is not realizable because of some hidden interdependency? I think not. Let's try to construct a counterexample. Suppose we have a_1=0, a_2=1, a_3=0. Condition: step1: 0 ok; step2: mex after step1 is 1, a2=1 <=1, and a2==mex, so mex becomes 2; step3: prefix after step2 is [0,1], mex=2, a3=0 <=2, ok. So condition holds for first three steps. Is there a way to get [0,1,0]? As argued earlier, yes: step1 empty subset ->0. step2 choose subset containing 0 -> mex=1 -> append 1. step3 we need to produce 0. With array [0,1], we can choose empty subset ->0. So yes.
What about a_1=0, a_2=0, a_3=2? Check: step1:0->mex=1; step2:a2=0 <=1, !=1 -> mex stays 1; step3: prefix [0,0], mex=1, a3=2>1 -> fails at step3. So output 3.
What about a_1=0, a_2=0, a_3=1, a_4=3? Step1:0->mex=1; step2:0<=1 -> mex=1; step3:1<=1, equals mex? Actually mex=1, a3=1 -> mex becomes 2; step4: prefix [0,0,1], mex=2, a4=3>2 -> fails at 4.
Now consider a more tricky: [0,2,0]? step1:0->mex=1; step2:2>1 -> fails at 2. So earlier.
Thus seems consistent.
But wait, there is a nuance: The mex of a multiset is defined as smallest non-negative integer not present. For the empty set, mex=0. So our initial mex=0.
Now, consider a step where a_i = 0. That's always possible by empty subset. So condition always holds. Good.
Now, what about a_i = 1? It requires that 0 is present before. So if we have a prefix without 0, impossible. But our condition captures that because mex would be >0 only if 0 present. Actually if 0 is missing, mex would be 0. So a_i=1 >0 -> invalid. So correct.
Now, is it possible that a_i is something like 10^9 and still <= mex? mex is at most i-1, so i-1 would need to be >=10^9, but n ≤ 100000, so impossible. So any a_i > n is automatically invalid. So we could also quick-check that if a_i > i-1, invalid, but our algorithm uses mex which is ≤ i-1.
Thus solution is O(n).
But let's test with some random generation: For any sequence that satisfies the condition, we should be able to produce it. I think it's correct.
However, there might be an edge: What if a_i = mex but mex > i? That can't happen because mex ≤ i. But consider i=1: mex=0, so a1=0 if equal.
All good.
Now, problem asks: "minimum step t such that he has definitely made a mistake on at least one of the steps 1, 2, …, t". If the sequence is realizable, output -1. So we output the first index where condition fails, or -1.
But we need to be careful: Could it be that condition fails at step t, but still it's possible that a mistake occurred earlier and step t could have been produced if earlier steps were different? The problem asks: "definitely made a mistake on at least one of the steps 1..t". That means: For the given array, we can deduce that among steps 1..t, at least one is wrong. If condition fails at step t, does it guarantee that there is a mistake in 1..t? Yes, because the array up to t is inconsistent: there is no possible way to have produced that prefix. Thus at least one step among 1..t must be wrong. However, could there be a smaller t' such that we already know a mistake must have occurred by step t'? That would be the minimal t such that prefix up to t is inconsistent. So we need the first index where the prefix becomes inconsistent. That's exactly the first i where condition fails. Because if for all j < i the prefix up to j is consistent, then we cannot claim a mistake before i. So the minimal t is that first i. So we simply output the first i where a_i > mex_{i-1}. If never, output -1.
Thus algorithm is trivial.
But wait: Are we sure that if the condition holds for all j <= i-1, then the prefix up to i-1 is realizable? Yes as argued.
Thus solution done.
Implementation: read n, read array a. Set mex=0. For i from 0 to n-1 (0-indexed) or 1-indexed, if a[i] > mex, print i+1 and return; else if a[i] == mex, mex++. After loop, print -1.
Time O(n). Memory O(1).
But let's double-check with more examples, including some that have large numbers.
Consider n=5, a = [0,0,0,0,0]. Condition: mex starts 0; step1:0==mex -> mex=1; step2:0<1 -> no change; step3:0<1; step4:0<1; step5:0<1. All a_i <= mex, so valid. Is it realizable? Step1: empty ->0. Step2: can we get 0 again? Yes empty subset. Step3,4,5 similarly. So valid.
Consider [0,1,2,3,0]. Step1:0->mex=1; step2:1->mex=2; step3:2->mex=3; step4:3->mex=4; step5:0<=4 -> ok. Realizable? After step4, array [0,1,2,3], mex=4. Step5: need 0 -> empty subset works. So valid.
Consider [0,1,3,2]. Step1:0->mex=1; step2:1->mex=2; step3:3>2 -> invalid step3. So answer 3. Could there be a different subset choice earlier that would allow 3 at step3? The prefix up to step2 is [0,1]; mex is 2. To get 3 at step3, we would need all numbers 0,1,2 present before step3. But we don't have 2. So impossible. So answer 3 correct.
Consider [0,2,1]? Step2 invalid. So answer 2.
Now, what about [0,1,0,2,1,3]? Step1:0->mex=1; step2:1->mex=2; step3:0<2 -> ok; step4:2==mex? mex currently? After step3, array [0,1,0]; numbers: 0,1; mex=2. So step4:2==mex -> mex=3; step5:1<3; step6:3==mex? mex=3? After step5, array includes 0,1,0,2,1 => numbers 0,1,2; mex=3; step6:3==mex -> mex=4. So valid.
Now consider a scenario where after some steps, we have numbers that fill gaps in a nonsequential order? But mex is monotonic; condition holds.
Thus seems robust.
But there is a nuance: The mex of the multiset is defined as smallest non-negative integer not present. In our reasoning, we used the property that if all numbers 0..M-1 are present, then mex = M. But is it possible that some numbers are repeated but we still have all 0..M-1 present? Yes. So our invariant holds.
Now, can we ever have a situation where after adding a value less than mex, the mex could increase because that value fills a missing number that was previously missing? No, because by definition mex is the smallest missing. So if we add a number less than mex, it must be a number that was already present (since all numbers less than mex are present). So it doesn't fill a gap.
Thus algorithm stands.
Let's also consider potential pitfalls: The problem statement says "subset of integers already added to the array" meaning subset of the values? Actually "subset of indices" which yields a multiset of integers. The mex of a multiset is defined as the smallest non-negative integer not presented (present). So duplicates don't matter. Our condition uses presence.
Edge case: Empty subset allowed. So mex of empty set is 0.
Thus algorithm done.
But wait: Could there be a scenario where the condition a_i <= mex(previous) holds, but we cannot produce a_i because the only way to produce it would require using some index that we might have "used" in a previous step? No, because subset choices are independent; there's no limitation on reusing indices across steps. At each step, we can pick any subset of indices from 1..m-1, regardless of previous choices. So no conflict.
Thus solution is correct.
Now, confirm with a more complex example where a_i is 0 and mex is large. Always possible via empty subset.
Thus answer.
Now, I'll write solution.
But before finalizing, I want to consider if there is any scenario where the mex after some steps might be > i? As argued, mex ≤ i. But is it possible that mex jumps by more than 1 when we add a number? For example, if we have numbers [0,2]? But 2 cannot be added because at step2, mex=1, so a2 must be ≤1. So can't. In a valid sequence, adding a number equal to mex only increments mex by 1 because all numbers less than mex are present, and numbers greater than mex are not present (since they would be > mex and would have violated earlier condition). But could there be a case where we have all numbers from 0..k-1 present and also have some number >k present? That would require that at some earlier step, we added a number > then-current mex. But that would have been invalid. So cannot. So mex always increases by exactly 1 when we add the current mex.
Thus algorithm is fine.
Now, consider the possibility of a_i being negative? No, a_i >=0.
Implementation details: We'll read input, loop, maintain mex (int). For each a_i, if a_i > mex, print i+1 (if 0-indexed) and exit. Else if a_i == mex, mex++. Continue. After loop, print -1.
Complexity O(n).
Let's test with given examples.
Example1:
n=4, a=[0,1,2,1]
mex=0
i0 a=0 -> a == mex? yes -> mex=1
i1 a=1 -> a == mex? yes -> mex=2
i2 a=2 -> a == mex? yes -> mex=3
i3 a=1 -> a <= mex? 1<=3 -> not equal -> nothing.
Loop ends -> -1.
Example2:
n=3, a=[1,0,1]
mex=0, i0 a=1 >0 -> print 1.
Example3: n=4, a=[0,1,2,239]
mex=0->1->2->3; i3 a=239>3 -> print 4.
Matches.
Now, more tests:
n=1, a=[0] -> mex=0, a0==0 -> mex=1; loop ends -> -1.
n=1, a=[1] -> a0=1>0 -> print 1.
n=2, a=[0,0] -> mex=0->1; i1 a=0<=1 -> not equal; loop ends -> -1.
n=2, a=[0,1] -> mex=0->1; i1 a=1==1 -> mex=2; -> -1.
n=2, a=[0,2] -> i1 a=2>1 -> print 2.
All good.
Now, think about any possibility that a mistake could be detected earlier than our condition? Suppose we have a prefix that satisfies condition, but there is some other constraint that makes it impossible? Let's try to find a counterexample.
We have condition a_i <= mex_{i-1}. Could there be a situation where this holds but still cannot be realized because the required subset to produce a_i cannot be formed due to some "ordering" constraints? For instance, to get a_i = k, we need to include one occurrence of each number 0..k-1. But what if some of those numbers appear only after we need to include them? But they are already in the prefix, so they exist. However, could it be that the only occurrence of some number j is at an index that we cannot include because we also need to avoid including some other number? But we can always choose which indices to include. If there is at least one occurrence of j, we can include that specific index. For numbers we want to avoid (like k, if present), we simply do not include any index with value k. So no conflict. So it's always possible.
Thus condition is sufficient.
Now, what about the empty subset? That's always allowed and gives 0. So a_i=0 always possible.
Therefore, the answer is indeed first index i where a_i > mex_{i-1}.
Thus the problem reduces to extremely simple.
But why would the problem be given as Codeforces problem? Possibly to trick people into overcomplicating. But indeed it's straightforward.
Wait, I recall a Codeforces problem: "Ildar and mex" or something similar? Actually I think it's Codeforces Round #1462? Not sure. The solution is indeed O(n) with mex.
But let's double-check the constraints: n up to 100000, a_i up to 1e9. So O(n) fine.
Edge Cases: When a_i == mex and mex becomes large, up to n. So mex fits in int.
Implementation: Use fast I/O.
Potential pitfall: The mex may become larger than n? Not possible because after n steps mex ≤ n. But if we have a sequence like all numbers from 0 to n-1 in order, mex becomes n after n steps. That's fine.
Now, we need to output the step number. So use 1-indexed.
Pseudo:
read n
mex = 0
for i in 1..n:
read a
if a > mex:
print i
return
elif a == mex:
mex += 1
print -1
That's it.
Now, let's verify with a more elaborate test: Suppose a = [0,1,3,2]. Our algorithm: step1:0->mex=1; step2:1->mex=2; step3:3>2 -> output 3. But could there be a different ordering of subsets that yields 3 at step3 if earlier steps had been chosen differently? But the array is fixed: a1=0, a2=1, a3=3. Regardless of how we chose subsets at steps1 and2, the resulting array after step2 is [0,1] (since a1,a2 are fixed). So the set before step3 is {0,1}. So mex is 2. So 3 impossible. So correct.
Now, consider a scenario where a_i is huge but less than mex? Impossible because mex ≤ i-1 ≤ n ≤ 1e5, so huge numbers > 1e5 cannot be ≤ mex. So they'd be invalid anyway.
Thus solution stands.
Before final answer, I'll read the problem statement again to ensure no misinterpretation: "On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array." It says "subset of integers already added to the array". Could it be interpreted as subset of the multiset of values (i.e., a subset of the set of numbers present, ignoring duplicates)? Actually "subset of integers already added" might mean a subset of the set of distinct integers? But the phrasing "subset of integers already added" is ambiguous. However, examples clarify: In step 4 of example1, they chose subset [0] (presumably a single element, not set). And earlier they say "subset of indices". So it's clear: we pick indices, so duplicates matter as separate elements, but subset selection includes at most one copy per index. So it's a subset of the multiset, but as a set of values it can include duplicates only if there are duplicate values at different indices. But mex depends on the set of values present (with duplicates irrelevant). So it's fine.
One more nuance: Could the subset be empty? Yes, they say possibly empty. So mex(empty)=0.
Thus all good.
Now, think about possibility of using the same index multiple times? No.
Thus answer is as derived.
I'll produce final answer.
But wait: Could there be a scenario where a_i = mex, but mex increases by more than 1 because there were already numbers equal to mex+1 present? But as argued, that cannot happen because all numbers are ≤ mex. So mex+1 is not present. So only +1.
Nevertheless, to be safe, we might implement a more robust mex update: after adding a_i == mex, we could while (mex in set) mex++. But set can be large; but we can maintain a boolean array of size n+2 for numbers that have been seen and are ≤ current max? But we argued it's unnecessary because numbers > mex cannot be present. But let's verify with a potential valid sequence: Could we ever have a number equal to mex+1 present before adding mex? Suppose current mex = k, meaning numbers 0..k-1 are present, k is missing. Could k+1 be present? For k+1 to be present, it must have been added at some earlier step. At that earlier step, the mex at that time was some value M'. Since k+1 > k, and k is missing now, it's possible that earlier M' was larger? Let's try to construct a scenario: Start: [0] -> mex=1. Add a2=2? But a2 must be ≤ mex=1, so cannot. So no. Therefore, by induction, at any point, all numbers in the set are ≤ mex. Because initially holds. Assume after i-1 steps, all numbers ≤ mex_{i-1}. At step i, we add a_i which must be ≤ mex_{i-1} (valid). So new element ≤ mex_{i-1} ≤ new mex? After addition, new mex is either mex_{i-1} (if a_i < mex_{i-1}) or mex_{i-1}+1 (if a_i = mex_{i-1}). In both cases, the new element is ≤ new mex. Also all previous numbers ≤ mex_{i-1} ≤ new mex. So invariant holds. So indeed no number > mex can appear. So while loop not needed.
Thus O(1) update.
Now, let's check if the condition a_i <= mex_{i-1} is equivalent to a_i < i. Not exactly: mex_{i-1} could be less than i-1 if some numbers missing. But a_i <= mex_{i-1} implies a_i <= i-1, but also stronger. So we can use the simpler condition to early reject if a_i >= i? Actually if a_i >= i, then definitely a_i > mex_{i-1} because mex_{i-1} ≤ i-1, so a_i >= i implies a_i > i-1 ≥ mex_{i-1}? Not exactly: mex_{i-1} could be exactly i-1? Possibly, but if a_i >= i, then a_i > i-1 ≥ mex_{i-1}. So indeed a_i >= i implies invalid. But the converse is not true: a_i could be less than i but still > mex_{i-1} if mex_{i-1} is smaller. So we cannot just check a_i < i; we need mex.
But for large a_i > n, it's invalid. So we could early reject if a_i > i-1 (since i-1 <= n-1). That might be a minor optimization but not needed.
Now, we should consider possible integer overflow? Not an issue.
Now, final answer: implement solve().
Edge: n=100000, reading with sys.stdin.
Now, ensure we output t as integer.
Now, I'll produce final answer.
But let's double-check with some random test: I'll write a quick mental simulation for n=5, sequence [0,2,1,3,4]? Step2: after step1 mex=1, a2=2>1 -> invalid at 2. So answer 2.
Now, suppose we have [0,0,2,1,3]? Step3: after step2 mex=1? Actually step1:0->mex=1; step2:0<1 -> mex stays 1; step3: a3=2 >1 -> invalid at 3.
Now, [0,1,1,2,3]? Step1:0->mex=1; step2:1==mex->mex=2; step3:1<=2, !=2 -> mex stays 2; step4:2==mex? mex=2? Actually after step3 mex=2, a4=2==mex -> mex=3; step5:3==mex? after step4 mex=3, a5=3==mex->mex=4. So valid. Is it possible? Let's construct: Steps: [0], [0,1], [0,1,1], [0,1,1,2], [0,1,1,2,3]. Step3: need 1, given [0,1] we can get 1 by subset containing 0 (or maybe also other). Step4: need 2, given [0,1,1], we have 0 and 1 present, can choose subset containing 0 and a 1 -> mex=2. Step5: need 3, given [0,1,1,2], we have 0,1,2 present, can choose subset containing 0,1,2 -> mex=3. So yes.
Thus algorithm holds.
Now, what about [0,1,0,3,2]? Step1:0->mex=1; step2:1->mex=2; step3:0<2; step4:3>2 -> invalid step4. So answer 4.
Alright.
Now, I'll write solution.
One more nuance: The problem statement says "minimum step t such that he has definitely made a mistake on at least one of the steps 1, 2, …, t". If the first inconsistency is at step i, then we output i because by then we know a mistake occurred among 1..i. Could there be a case where the prefix is inconsistent but the first inconsistent step is not the first step where a_i > mex, because maybe earlier steps might also be inconsistent but we don't detect until later? But our detection is at the first step where condition fails; that is the smallest i such that prefix up to i is inconsistent. Because if condition holds for all j < i, then prefix up to i-1 is consistent. So i is the smallest t with inconsistent prefix. So it's the answer.
Now, finalize.
But wait, there is a subtlety: The condition we derived is necessary and sufficient for the existence of a sequence of subsets that yields the prefix. However, is it possible that the prefix is consistent (so there exists some way to choose subsets) but the actual process Ildar might have used could have made different subset choices, and we need to detect a mistake based on the given array only? The problem asks: "determine for a given array a_1..a_n the minimum step t such that he has definitely made a mistake on at least one of the steps 1..t, or determine that he could have obtained this array without mistakes." If the array can be obtained by some sequence of choices, then it's possible he made no mistakes. So we output -1. So we just need to check if there exists any sequence of choices that yields exactly that array. That's exactly our realizability condition.
Thus solution is correct.
Now, I'll produce final answer.
Potential pitfalls: Input size, use fast I/O. Use Python's sys.stdin.read.
Implementation in Python:
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data: return
n = int(data[0])
a = list(map(int, data[1:]))
mex = 0
for i in range(n):
if a[i] > mex:
print(i+1)
return
elif a[i] == mex:
mex += 1
print(-1)
That's it.
Now, I'll write the final answer accordingly. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
n = int(data[0])
a = list(map(int, data[1:]))
mex = 0
for i, val in enumerate(a):
if val > mex:
print(i + 1) # step numbers are 1-indexed
return
if val == mex:
mex += 1
print(-1)
if name == "main":
solve()