We need to find the MEX of a string, defined as the shortest string that doesn't appear as a contiguous substring (i.e., a substring that is contiguous? Wait: The problem says "contiguous substring" but then defines substring: "A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end." That is the standard definition of substring (contiguous). Usually "substring" is contiguous. But they also say "contiguous substring" to emphasize? However the definition they gave for substring is contiguous: deletion from beginning and end only, not arbitrary deletions. So it's just standard substring.
Thus we need the shortest string (by length) that does NOT occur as a substring of the input string. Among those of the same minimal length, choose lexicographically smallest. Also empty string does NOT count as valid MEX (so we start from length 1). So we need to find the smallest missing substring.
We have constraints: total n across test cases ≤ 1000. n per test up to 1000. So we can afford O(n^2) or similar per test.
Goal: find the smallest L such that not all possible strings of length L appear. Since alphabet size is 26, total possible strings of length L is 26^L. For L small, we can check. Since n is up to 1000, the number of distinct substrings length L is at most n - L + 1 (if all distinct). But we don't need distinct; we need to see which ones are present.
Simplest approach: For each length L starting from 1 upwards, generate all substrings of length L from the input, put them in a set. Then check all possible strings of length L over alphabet 'a'..'z' in lexicographic order, and see if any is not in the set. The first missing one is the answer. Since n is only 1000, the maximum length L we might need to consider? The total number of possible strings grows exponentially. For L=1, there are 26 possibilities, if all appear then need L=2 (676 possibilities). If the string length n is at most 1000, the maximum possible substrings length L is n-L+1. For L=3, maximum distinct substrings is at most 1000, but there are 17576 possibilities, so definitely there will be missing strings at length 3 if not earlier. But maybe the string contains all length-1? There are only 26 letters. It's possible that the string uses all 26 letters (like the first sample: "qaabzwsxedcrfvtgbyhnujmiklop" has all letters? Actually it has 26 letters, each appears once except a maybe twice? It contains all 26 letters? Let's check: q a a b z w s x e d c r f v t g b y h n u j m i k l o p -> that's 28 length, but it contains all letters? There is 'c'? Yes. It includes all? Probably it's a scrambled alphabet: q a a b ... but it has duplicate a and b, but includes all 26 letters? The output is "ac". For length 1, do all letters appear? The string includes 'a', 'b', 'c', ... up to 'z'? Let's verify: letters: q, a, a, b, z, w, s, x, e, d, c, r, f, v, t, g, b, y, h, n, u, j, m, i, k, l, o, p. It has 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b' again. So it includes all 26 letters. So length-1 all appear, so MEX length is at least 2. Then we need to find the smallest missing string of length 2. The output is "ac". So indeed "ac" is missing among the substrings of length 2.
Thus we can implement: For each test case, iterate L from 1 upwards. For each L, generate all substrings of that length: for i in 0..n-L, substring s[i:i+L]. Add to a set. Since n <= 1000, total substrings overall O(n^2) worst-case but we will stop early. Actually we need to generate substrings for each L separately; we can precompute all substrings up to some max L. But we can also generate on the fly.
But note: The total n across tests is only 1000, so O(n^2) overall is fine.
Important: We need to check lexicographically smallest missing string of length L. So after we have set of present substrings for length L, we can generate strings of length L in lexicographic order (like by counting in base-26, from aaaa... up to zzzz...), but the number of possibilities may be huge for L large (26^L). But we will stop when L is small because by pigeonhole principle there must be a missing string when 26^L > n - L + 1 (the maximum number of distinct substrings of length L). Actually we need to guarantee we will find missing before L becomes too large. The maximum length L we might need to check: Since n <= 1000, the number of distinct substrings of length L is at most n - L + 1, which is at most 1000. For L=3, 26^3 = 17576 > 1000, so there must be missing strings at L=3 if not earlier. But if all 26^2=676 length-2 strings are present? That would require the string length to be at least 676 + 1 = 677 (since substrings of length 2 need overlapping). Actually to have all 676 distinct length-2 strings, the string must be at least 677 characters, but could be more due to repetitions? But maximum distinct substrings length 2 is limited by n-1. So if n < 677, it's impossible to have all 676 length-2 substrings. But n can be up to 1000, so it's possible to have all length-2 strings if n >= 677? But even if n=1000, it's possible to include all 676 substrings? Possibly yes, if the string is a de Bruijn sequence of order 2 over 26 letters. The length needed for a de Bruijn sequence that covers all possible 2-grams is 26^2 + 1 = 677. So if the string is a de Bruijn sequence of order 2, it would contain all 2-letter substrings. However, the sample first test case has n=28, so definitely not all length-2 substrings present. The second test case: n=13, output "f" (single character), so length 1 missing. The third: n=10, output "b". So length 1 missing as well.
Thus in practice, L will be at most maybe 3 for n=1000? Because even if all length-2 are present, we might need L=3. But is it possible that all length-3 strings are present? That would require 26^3 = 17576 distinct substrings, but n-L+1 <= 998 maximum, so impossible. So L <= 3 for any n <= 1000. Actually for n=1000, the maximum distinct substrings of length 3 is at most 998, which is far less than 17576, so there will be many missing. So the MEX length L is at most 3. But what about the case where length 1 missing? Then L=1. If length 1 all present, then we check length 2. It's possible length 2 all present if the string is a de Bruijn sequence of order 2 and n >= 677. But note: n can be at most 1000, so it's possible. Then we need to check length 3. So worst-case L=3.
But wait, could it be that length 1 present, length 2 present (all 676), and length 3 missing, but the lexicographically smallest missing string of length 3 might be something like "aaa"? Could "aaa" be missing? Possibly. But we must output that. So we need to generate strings of length 3 in lex order and check if present. That's 26^3 = 17576 possibilities, which is okay given total sum n ≤ 1000 and t ≤ 1000? But 17576 per test could be heavy if many tests require length 3. However, the total sum of n is 1000, so the number of test cases that could possibly have n >= 677 and also include all length-2 substrings is very limited. Actually if total sum of n is 1000, there can't be many large strings. So we can safely generate all 17576 strings in worst-case for maybe one or two test cases. Even if we did it for all tests, 1000*17576 ≈ 17.5 million, which is maybe okay in Python? Might be borderline but likely acceptable given time limit? But we can optimize: we don't need to generate all strings if we can find missing efficiently using the set of present substrings.
Alternate approach: For each L, we can iterate through all present substrings, convert each to an integer (base-26 representation) and mark in a boolean array of size 26^L. Then find the first index not marked. That could be memory heavy for L=3: 17576 booleans, which is fine. For L=2: 676; L=1: 26. So we can do this.
But we need to handle variable L: we start with L=1, generate array size 26, check each character present? Actually we can just gather all characters in the string, set present, then find missing char from 'a' to 'z'. If none missing, go to L=2.
For L=2: we can create a boolean array of size 26*26 = 676. Iterate over all substrings of length 2, convert to index (c1-97)*26 + (c2-97). Mark true. Then scan indices 0..675, convert back to string (two chars) to find first missing. If any missing, output that string, else proceed to L=3.
For L=3: create array size 17576. Iterate substrings length 3, compute index = (c1-97)*26^2 + (c2-97)*26 + (c3-97). Mark true. Then scan for first false. Output corresponding string of length 3.
Given that n is at most 1000, substrings of length 3 are at most 998, so marking is cheap.
But is it guaranteed that we will find a missing at L=3? Yes, because there are 17576 possible strings, but at most 998 present, so definitely missing.
Edge Cases: Could MEX be length >3 if n is larger? But constraint sum n ≤ 1000, but if a single test has n=1000, length 3 still missing. However, could it be that the string includes all possible strings of length 1,2,3? That would require at least 26^3+2 = 17578 characters, but n is only 1000, impossible. So L ≤ 3.
Thus we can implement straightforward.
But wait, the problem statement says "shortest string that doesn't appear as a contiguous substring in the input". This includes the empty string? They say empty substring does NOT count as valid MEX. So we start from length 1. So indeed we only need to consider lengths 1,2,3.
But is there any scenario where the string contains all possible substrings of length 1,2,3? As argued, impossible due to size. So answer length ≤ 3.
Thus solution: For each test case:
- Read n and string s.
- Create set of chars: check if all 26 letters appear. If not, find smallest missing letter (lexicographically smallest) among 'a'..'z' that is not present. Output that single character.
- Else (all 26 letters present), go to length 2.
- Create bool array present2[676] = False.
- For i from 0 to n-2:
idx = (ord(s[i])-97)*26 + (ord(s[i+1])-97)
present2[idx] = True
- Iterate i from 0 to 675:
if not present2[i]:
first = i//26, second = i%26
output chr(first+97)+chr(second+97)
break
- If we break, done. Else (all 2-length present), go to length 3.
- For length 3:
- Create bool array present3[262626] = False. Since 17576 is not too big, allocate as list of bool. Could also use Python set but array scanning is fine.
- For i from 0 to n-3:
idx = (ord(s[i])-97)2626 + (ord(s[i+1])-97)*26 + (ord(s[i+2])-97)
present3[idx] = True
- Iterate i from 0 to 17575:
if not present3[i]:
first = i // (2626)
remainder = i % (2626)
second = remainder // 26
third = remainder % 26
output chr(first+97)+chr(second+97)+chr(third+97)
break
That's it.
But careful: For length 2, we need to ensure we handle the case where n<2 (but n>=1). If n=1, then length 2 substrings cannot exist, so present2 all false, so the first missing would be "aa"? But note: If n=1, all characters? length 1 may not have all 26 characters, so we would output a single missing character. So we never go to length 2 if length 1 missing. So we only go to length 2 if all 26 letters appear. That implies n>=26? Actually to have all 26 letters, string must contain at least 26 characters. So if n<26, we will output missing char at length 1, so fine.
So for length 2, we assume n>=2 because we have already checked all 26 letters present, which implies n>=26, so n>=2 automatically.
Similarly for length 3, we only go there if all length-2 strings are present, which requires n>=677. So n>=677, thus n>=3 automatically.
Thus safe.
But what about strings that have all 26 letters but not all length-2 strings? Then we will output a length-2 missing, no need for length 3.
Implementation details: Because total sum n is small, we could also use Python's set of substrings for each length. For length 1, just set of characters. For length 2, we can store all substrings of length 2 in a set and then generate missing by iterating over all two-letter combos in nested loops until find one not in set. That might be simpler: For L=2, iterate c1 in 'a'..'z', c2 in 'a'..'z', form string c1+c2, if not in set, output and break. That's 676 checks per test case that goes to L=2. That's fine. For L=3, that would be 17576 checks, still okay. However, using set lookups may be slower but still acceptable. But we can also use boolean array for speed.
Since total sum n is 1000, the number of test cases with L=3 would be at most maybe 1 (if one string length ≥ 677 and is a de Bruijn sequence). 17576 checks with set membership (O(1) average) is fine. But if there are many test cases, the total checks across all tests may be more: Suppose there are many small test cases that go to L=1 only, so no many checks. If there are many medium test cases that go to L=2, 676 checks each. If t=1000 and all go to L=2, that's 676k checks, which is okay. Actually worst-case: t=1000, each with n just enough to have all 26 letters but not all length-2, so they go to L=2 but will find missing quickly maybe before scanning all? We must scan from "aa" upwards until we find missing. In worst-case, missing might be near the end like "zz". But we still have to check each until find. So up to 676 checks per test. 1000676 = 676,000, fine. For L=3: 100017576 = 17,576,000, still okay within 1 second? Possibly okay in Python if optimized? Might be borderline but likely fine given that sum n is 1000, meaning many test cases with large n cannot exist because total length is limited. So there can be at most one test case with n close to 1000, the others must be very small. So overall operations will be far less. So using sets is simpler and less error-prone.
But careful: The substring set for L=3 would contain up to 998 strings. Checking membership for 17576 candidates might be okay. But we can speed up by using boolean array as described.
Let's adopt the boolean array approach because it's deterministic and efficient. However, we need to allocate an array of size 17576 for each test that reaches L=3. Since only maybe one test will, it's fine. We'll also need to convert indexes.
Implementation Plan:
For each test case:
- n, s.
- Compute present1 = [False]*26
- For ch in s: present1[ord(ch)-97] = True
- For i in range(26):
if not present1[i]:
print(chr(i+97))
break
else: (all present)
length 2
present2 = [False]*676
for i in range(n-1):
idx = (ord(s[i])-97)*26 + (ord(s[i+1])-97)
present2[idx] = True
found = False
for idx in range(676):
if not present2[idx]:
c1 = idx // 26
c2 = idx % 26
print(chr(c1+97)+chr(c2+97))
found = True
break
if not found:
# length 3
present3 = [False]17576
for i in range(n-2):
idx = (ord(s[i])-97)2626 + (ord(s[i+1])-97)26 + (ord(s[i+2])-97)
present3[idx] = True
for idx in range(17576):
if not present3[idx]:
c1 = idx // (2626)
r = idx % (2626)
c2 = r // 26
c3 = r % 26
print(chr(c1+97)+chr(c2+97)+chr(c3+97))
break
That's it.
But consider potential off-by-one: n-2 loop for length 3: range(n-2) goes i from 0 to n-3 inclusive, correct.
Now, is there any scenario where MEX length could be 0? The problem says empty substring does NOT count as valid MEX. So we ignore.
Now confirm with sample:
Test 1:
n=28, string includes all letters. So present1 all true -> go length 2.
Compute present2: substrings length 2 of this string? Let's check if "ac" missing? We'll compute. The output is "ac". Our algorithm will iterate idx from 0 to 675. "aa" corresponds to 0,0. "ab" maybe present? We'll output first missing. Should be "ac". That is consistent.
Test 2:
n=13, string "cleanairactbd". Let's check presence of letters: c,l,e,a,n,a,i,r,a,c,t,b,d. Contains a,b,c,d,e,i,l,n,r,t. Missing f,g,h,j,k,m,o,p,q,s,u,v,w,x,y,z. Smallest missing is 'f'. So output "f". Good.
Test 3:
n=10, string "aannttoonn". Check letters: a,n,t,o. Missing many. Smallest missing is 'b'. Output "b". Good.
Thus algorithm works.
Now verify complexity: O(n) for scanning for each length, plus scanning boolean array. For length 3 scanning 17576, but only when necessary. With total n sum 1000, overall fine.
Potential issues: Python recursion? Not used. Input reading large? Use sys.stdin.
Now, is there any trick? The definition of substring says "deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end." So it's contiguous substring indeed. So our approach correct.
Edge Cases: String length 1000 containing all 26 letters and all 676 length-2 substrings. Then we compute present2 all true. We then go to length 3. For length 3, we compute present3 and find the first missing. Which one is lexicographically smallest? That would be the smallest string of length 3 not present. Since we iterate idx from 0 to 17575, corresponding to "aaa", "aab", ... "zzz". So we will find the lexicographically smallest missing. That's correct.
Now, confirm that the set of substrings of length L is indeed considered as contiguous substrings. Yes.
But there is nuance: Lexicographic order: For strings of different lengths, we prioritize shorter length. So we find smallest L. So our incremental check works.
Now, the sum of n over all test cases ≤ 1000. So we don't need to worry about high memory across tests.
Let's code.
Potential optimization: For length 2 and 3, we can early break if we find a missing. We already do.
Now, let's test some custom cases.
Case 1: n=1, s="a". present1: 'a' present, missing 'b'? Actually 'a' present, others missing, smallest missing is 'b'. Output "b". Good.
Case 2: n=26, s is permutation of alphabet. Then all letters present, go length 2. Since only 26 length, maximum distinct length 2 substrings is 25. So many missing. The smallest missing might be "aa"? Does "aa" appear? In permutation, letters are all distinct, so no "aa". So output "aa". Good.
Case 3: n=677, s is de Bruijn sequence of order 2 over 26 letters. Then all 676 length-2 substrings present. So go length 3. Now, what is the lexicographically smallest missing length-3 string? It might be something like "aaa"? Possibly "aaa" does not appear because de Bruijn of order 2 doesn't guarantee triple repeats. Actually a de Bruijn sequence of order k covers every possible substring of length k exactly once (or at least once). For order 2, it covers all pairs, but does it necessarily cover all triples? No, because the length is 26^2+1=677, and the number of length-3 substrings in such a sequence is 677-2=675, which is less than 17576. So many triples missing. The lexicographically smallest missing triple is likely "aaa" unless "aaa" appears. Could "aaa" appear? In a de Bruijn sequence of order 2 over alphabet size 26, it's possible that "aaa" appears if the sequence contains three consecutive 'a's. Since the sequence is an Eulerian cycle in de Bruijn graph. It might contain "aaa" if there is a state 'aa' and then transition to 'a?' such that the next character is 'a', i.e., from node 'aa' we follow edge to node 'a?'? Actually de Bruijn graph nodes are length-2 strings, edges represent length-3 strings. The sequence covers each edge exactly once. The edge from node 'aa' to node 'aa' corresponds to the triple 'aaa'. Is there an edge from 'aa' to 'aa'? Yes, because appending 'a' to 'aa' gives 'aa' (shift left and add 'a'). So that edge exists. In a Eulerian cycle, we may or may not include that edge depending on the cycle. It is possible to include it, but not necessary. Since we need to traverse each edge exactly once, if we include it, then "aaa" will appear exactly once. But does the standard de Bruijn sequence include all edges, so it must include "aaa". Actually a de Bruijn sequence of order k over alphabet of size s is a cyclic sequence where every possible length-k string appears exactly once as a substring (considering wrap-around). For a linear sequence of length s^k + k - 1, we also cover all substrings (if we consider the cyclic version, we can linearize by repeating first k-1 characters at the end). Typically a de Bruijn sequence will include all possible substrings of length k, not necessarily all of length k+1. But the sequence is of length s^k + k - 1. For order 2, we have length 26^2 + 1 = 677? Actually for linear de Bruijn sequence (non-cyclic) it's s^k + k - 1 = 26^2 + 1 = 677. This linear sequence will contain each length-2 substring exactly once (when considering the sequence as a linear string, not cyclic). It will also contain many length-3 substrings, but not all. Since it contains each length-2 exactly once, the total length-3 substrings are 677-2 = 675. There are 17576 possible triples, so many missing. The lexicographically smallest missing might be "aaa" if "aaa" is not among those 675 triples. But is "aaa" possible to be among them? "aaa" corresponds to the edge from 'aa' to 'aa'. In the de Bruijn graph, nodes are 2-grams, edges are 3-grams. The Eulerian cycle that covers each edge exactly once (if we want to cover all 3-grams) would need to have 26^3 edges, but we are not covering all 3-grams; we are covering all 2-grams, which corresponds to a Hamiltonian path? Actually standard de Bruijn sequence for order k covers each k-gram exactly once; it corresponds to an Eulerian cycle in the de Bruijn graph of order k-1? Let's recall: A de Bruijn sequence of order k (i.e., covering all k-length strings) can be constructed from an Eulerian cycle in the de Bruijn graph where nodes are (k-1)-length strings and edges are k-length strings. For k=2, nodes are length-1 strings (single characters), edges are length-2 strings. Actually typical: For order k, the de Bruijn graph B(k-1, s) has nodes (k-1)-mers, edges represent k-mers. So for k=2, nodes are 1-character strings, edges are 2-char strings. That graph has s nodes and s^2 edges. An Eulerian cycle (which exists because each node has indegree=outdegree=s) gives a cyclic sequence of length s^2 that contains every 2-mer exactly once (as a cyclic sequence). To get linear, we add the first character. That yields length s^2 + 1? Actually the standard de Bruijn sequence length is s^k (cyclic) or s^k + k - 1 (linear). For k=2, s^2 = 676. The cyclic sequence length 676 contains each 2-mer exactly once when considering cyclic substrings. To get a linear string of length 676 + 1 = 677 that contains each 2-mer exactly once (as a linear substring), we take the cyclic sequence and repeat the first character at the end. So that's the de Bruijn sequence. In this construction, the nodes are single characters, edges are pairs. The Eulerian cycle uses each edge exactly once. That means each possible pair appears exactly once. But what about triples? In the linear string, the triples are formed by consecutive edges: i.e., if we have pairs (a,b) and (b,c), that gives triple abc. The triple "aaa" would require edges (a,a) and (a,a) consecutively, i.e., after taking edge 'aa', we move to node 'a' and then take another edge 'aa'. That is possible if the cycle goes from node 'a' via edge 'aa' back to node 'a', and then again via edge 'aa'. But in an Eulerian cycle, we traverse each edge exactly once, so we cannot traverse edge 'aa' twice. So we can only have at most one occurrence of the edge 'aa'. For triple 'aaa', we need two consecutive edges both 'aa', which would require using edge 'aa' twice, not allowed. Thus in a standard de Bruijn sequence covering each 2-mer exactly once, the triple 'aaa' cannot appear because it would require two 'aa' edges in a row. However, could it appear if we have a triple that spans across the wrap? In the linear version, the triple formed by the last two characters and the first character? Actually the linear string of length 677, substrings are defined linearly, no wrap. So triple 'aaa' would be three consecutive characters all 'a'. That would imply two overlapping pairs: positions i,i+1 = 'aa' and i+1,i+2 = 'aa'. That requires two occurrences of 'aa' in the string, but we only have one occurrence of each pair exactly once (since all pairs appear exactly once). So indeed 'aa' appears exactly once. To have two 'aa's overlapping, we would need at least two distinct occurrences of 'aa' (non-overlapping but overlapping? Actually if we have a run of three a's, that would contain two overlapping 'aa' substrings: the first starting at position 1, and the second starting at position 2. That means the pair 'aa' appears at two distinct positions, which would be two occurrences, contradicting that each pair appears exactly once. Therefore, in such a de Bruijn sequence, 'aaa' cannot appear. So the lexicographically smallest missing triple is indeed "aaa". Our algorithm would output "aaa" if it's missing. But wait, is it guaranteed that "aaa" is missing? Possibly, but there might be even smaller? Lexicographically, "aaa" is the smallest string of length 3. So if it's missing, it's the answer. But if for some reason "aaa" appears, then we need to check "aab", etc. Could "aaa" appear in a string that contains all 2-mers exactly once? As argued, it cannot because it would require two occurrences of 'aa'. However, could the string contain all 2-mers but not necessarily exactly once; they could appear multiple times? For example, a longer string could contain all 676 pairs, but some may appear more than once. For instance, if we construct a string that is a de Bruijn sequence but then add extra characters, it might still contain all pairs, but also may have extra occurrences. Could such a string include "aaa"? Yes, if we add an extra 'a' somewhere, we could get "aaa". For instance, take a de Bruijn sequence that covers all pairs exactly once, and then insert an extra 'a' between two characters to create "aaa". But then the pairs may change: the sequence might still have all pairs? Possibly some pairs might be added, but still all pairs are present. It is possible to have a string of length >677 that contains all 676 pairs, and also contains "aaa". In that case, "aaa" might be present, so the missing triple could be something else like "aab" if that missing. But is it possible to have all 676 pairs and also have "aaa"? Yes, if the string has at least one occurrence of "aaa", then it contains two occurrences of "aa" (the overlapping ones). That's fine as long as all pairs are present. So the de Bruijn property does not forbid extra occurrences. So the lexicographically smallest missing triple might not be "aaa" if "aaa" appears. However, we can still find it by scanning from 0 upwards. Our algorithm will correctly output the first index that is false.
Thus fine.
Now, consider potential pitfalls: For L=2, we need to ensure that we consider substrings of length 2 exactly as they appear, including overlapping. Our loop does that.
Now, memory: present3 array of size 17576 booleans. In Python, using list of bools, each bool is an object? Actually list of booleans are Python objects, but 17576 is small. Alternatively, we can use bytearray for efficiency. But not necessary.
Time: For each test with L=3, we do O(n) + 17576 iterations for scanning. That's fine.
Now, we should be careful about reading input. Use sys.stdin.read or sys.stdin.readline.
Now, I'll write the solution accordingly.
But wait: There is a nuance: The problem says "shortest string that doesn't appear as a contiguous substring in the input". This includes the empty string? They explicitly say empty substring does NOT count. So we start from length 1.
Now, confirm that our algorithm for length 1: We check each character in the string and set present for letters. Then we find smallest missing. However, what if the string contains all 26 letters? Then we go to length 2. Good.
Edge case: n=0? Not possible because n≥1.
Now, potential bug: In Python, when we iterate for i in range(26) and break, we need to know if we broke or not. We can use for-else construct: for... if not present: print and break; else: (if loop completes without break) then go to length 2. That's fine.
Similarly for length 2: We iterate idx from 0 to 675, if not present2, print and set a flag found = True and break. If loop ends without break, we go to length 3. Use a flag or use for-else.
Better: Use for-else to avoid flag. For example:
for i in range(26):
if not present1[i]:
print(chr(i+97))
break
else:
# all present
present2 = [False]*676
for i in range(n-1):
idx = (ord(s[i])-97)*26 + (ord(s[i+1])-97)
present2[idx] = True
for idx in range(676):
if not present2[idx]:
print(chr(idx//26+97)+chr(idx%26+97))
break
else:
present3 = [False]17576
for i in range(n-2):
idx = (ord(s[i])-97)2626 + (ord(s[i+1])-97)26 + (ord(s[i+2])-97)
present3[idx] = True
for idx in range(17576):
if not present3[idx]:
c1 = idx // (2626)
r = idx % (2626)
c2 = r // 26
c3 = r % 26
print(chr(c1+97)+chr(c2+97)+chr(c3+97))
break
Yes.
Now, note that for length 3 we need to compute idx properly. Use pow = 26*26 = 676.
Let's code.
Testing with sample:
We'll run mentally:
Case 1: n=28, s=... all letters present -> go length 2. present2 computed. The first missing index? likely corresponds to "ac". "a"=0, "c"=2 -> index 0*26+2=2. But "aa" index 0, "ab" index 1, etc. So if "aa" and "ab" present? Let's check: does string contain "aa"? The string is "qaabzwsxedcrfvtgbyhnujmiklop". At the beginning: "q a a b ..." So substring starting at index1: "aa" appears. So "aa" present. "ab" appears as "ab"? At index2: "ab"? Actually indices: 0:'q',1:'a',2:'a',3:'b',... So substring at 1-2: "aa", 2-3: "ab"? 2:'a',3:'b' => "ab" present. "ac"? To have "ac", we need 'a' followed by 'c'. Does that occur? Check: the letters: after 'a's, we have 'b', then 'z', etc. There is 'a' somewhere later? There is 'c' at position 10? Actually string: q a a b z w s x e d c r f v t g b y h n u j m i k l o p. Let's list indices and chars:
0: q
1: a
2: a
3: b
4: z
5: w
6: s
7: x
8: e
9: d
10: c
11: r
12: f
13: v
14: t
15: g
16: b
17: y
18: h
19: n
20: u
21: j
22: m
23: i
24: k
25: l
26: o
27: p
Now substrings of length 2:
(0) "qa"
(1) "aa"
(2) "ab"
(3) "bz"
(4) "zw"
(5) "ws"
(6) "sx"
(7) "xe"
(8) "ed"
(9) "dc"
(10) "cr"
(11) "rf"
(12) "fv"
(13) "vt"
(14) "tg"
(15) "gb"
(16) "by"
(17) "yh"
(18) "hn"
(19) "nu"
(20) "uj"
(21) "jm"
(22) "mi"
(23) "ik"
(24) "kl"
(25) "lo"
(26) "op"
Now "ac" is not in this set. So the first missing in lexicographic order: Let's list all possible from "aa", "ab", "ac", ... "az". "aa" present, "ab" present, "ac" missing => index 2 (since 'a'=0, 'c'=2). So output "ac". Good.
Now, code will do present2[0]=True, present2[1]=True, present2[2]? false. So idx=2 triggers output. Works.
Now, is there any possibility that the MEX length could be >3 if the string is such that all substrings of lengths 1,2,3 exist? That would require at least 26^3+2 = 17578 characters, which exceeds 1000. So impossible.
But consider the possibility that the string might be such that all substrings of length 1 and 2 exist, but there is no substring of length 3? Wait, that cannot happen because if the string length is at least 3, there are substrings of length 3 (unless n<3). If n>=3, there will be substrings of length 3. But the MEX length is the shortest missing, so if length 3 substrings are all present? That would need all 17576 possible strings of length 3 to appear, but n is at most 1000, so not possible. So length 3 will always have missing if we get to that point. So we are safe.
Now, just to be thorough: Could the MEX length be 0? They say empty substring does NOT count, so no.
Now, confirm the definition: The MEX is the shortest string that doesn't appear as a contiguous substring. They say "contiguous substring" but then define substring as deletion from beginning and end, which yields contiguous substrings. So it's consistent.
Now, additional consideration: The input size: t up to 1000, sum n up to 1000. So many test cases with tiny strings. Our algorithm for each test case will allocate arrays of size 676 or 17576 only if needed. But if many test cases go to length 2? For each such test, we allocate present2[676] and then scan. That's okay.
But we can also implement with sets to avoid allocation, but either is fine.
Now, test with random small strings to ensure correctness.
Edge case: String includes all letters, and also all length-2 strings? Example: n=677 and the string is constructed to contain all length-2 strings. Let's try to construct a simple one: For alphabet size 3 (a,b,c), de Bruijn sequence for order 2 has length 9+1=10? Actually 3^2+1=10. For 3 letters, all 9 pairs appear. For 26 letters, length 677. So we need to ensure our algorithm works for such case. We'll test with small alphabet maybe? But actual alphabet is 26, but we can test with a smaller custom test? Not needed.
Now, potential performance: for each test that goes to length 3, we allocate present3 of size 17576. In Python, that's about 17576 * 1 byte if using bytearray, but using list of bool might be about 28 bytes per entry? Actually list of bool stores Python objects, but 17576 * 8 bytes (if using array of pointers) is ~140KB, which is fine. But across tests, we should not keep them; we allocate within loop and discard.
Now, note: The sum of n is 1000, but t can be 1000. In the worst case, there could be 1000 test cases each with n=1. Then we only check length 1, no arrays. So fine.
Now, implement.
Potential improvements: Use ord conversion once? But not necessary.
Now, let's write code.
Pseudo:
import sys
def solve():
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
s = next(it).strip()
# length 1
present1 = [False]26
for ch in s:
present1[ord(ch)-97] = True
for i in range(26):
if not present1[i]:
out.append(chr(i+97))
break
else:
# length 2
present2 = [False]676
for i in range(n-1):
idx = (ord(s[i])-97)26 + (ord(s[i+1])-97)
present2[idx] = True
for idx in range(676):
if not present2[idx]:
out.append(chr(idx//26 + 97) + chr(idx%26 + 97))
break
else:
# length 3
present3 = [False] * (262626)
base = 2626
for i in range(n-2):
idx = (ord(s[i])-97)base + (ord(s[i+1])-97)26 + (ord(s[i+2])-97)
present3[idx] = True
for idx in range(262626):
if not present3[idx]:
c1 = idx // base
r = idx % base
c2 = r // 26
c3 = r % 26
out.append(chr(c1+97) + chr(c2+97) + chr(c3+97))
break
sys.stdout.write("\n".join(out))
if name == "main":
solve()
Now, check that base = 26*26 = 676. For idx calculation: idx = (c1)*base + (c2)*26 + c3. Good.
Now, verify with sample input.
We'll simulate.
But we should also consider the possibility of string length being exactly 2. For length 2, n=2, then when we check length 2, we will have one substring (positions 0-1). present2 will have exactly one true. Then we scan for first missing. That's fine. But we only go to length 2 if all letters are present; n=2 cannot have all 26 letters. So we won't go to length 2 for n=2 anyway. So no issue.
Now, what about n=26 exactly and all letters distinct? Then all letters present, go to length 2. n-1 = 25, so we have 25 substrings length 2. present2 has up to 25 true. Then scanning will find first missing, likely "aa" as noted.
Now, but consider a case where the string length is large enough to contain all letters but some letters appear only once. That's fine.
Now, we need to ensure that we treat substrings correctly for overlapping. Already done.
Now, are there any pitfalls regarding lexicographic order when generating strings via index order? Since we assign index as base-26 number with most significant digit being first character, scanning from 0 to 26^L-1 yields strings in lexicographic order: because for strings of fixed length, the lexicographic order corresponds to numeric order in base-26 if we treat 'a'=0, 'b'=1, ... 'z'=25. Yes: "aa...a" (0) is smallest, then "aa...b" (1), ..., "aa...z", then "aba..."? Wait: For L=2, index = c1*26 + c2. As index increases, the strings are: (0,0), (0,1), ..., (0,25), (1,0), (1,1), ... That corresponds to lex order? Let's check: Lex order compares first character first. So strings starting with 'a' (c1=0) come before those starting with 'b' (c1=1). Among those with same first char, second char compared. So indeed the order: for c1 fixed, increasing c2 yields increasing strings. And as index runs, we first go through c1=0 with c2 from 0..25, then c1=1 with c2 0..25. That's exactly lexicographic order. For L=3, similar. So scanning index from 0 upward yields lexicographically smallest missing.
Thus correct.
Now, double-check: For length 1, we output smallest missing letter. That's lexicographically smallest because we scan from 'a' to 'z'. Good.
Now, test with some custom:
Input:
1
4
abcd
This string contains letters a,b,c,d. Missing e (smallest). Output "e". Our code: present1[0]=True,1,2,3 True, others false. i=0..3 present, i=4 not present -> output 'e'. Good.
If we had all letters but not all length2: e.g., "abcdefghijklmnopqrstuvwxyz" (length 26). All letters present. Substrings length2: "ab","bc","cd",..., "yz". Missing "aa", so output "aa". Our code will output idx=0 missing, print 'aa'.
Now, if we had a string that includes all 676 pairs: need to generate de Bruijn. Let's test with small alphabet of size 2 for mental check: suppose alphabet = {'a','b'}, but problem uses 26. Not needed.
Now, ensure we handle the sum of n constraint: The code loops over n-2 only when length 3 needed, which would be for large n. So total operations are limited.
Now, potential improvement: For length 3 scanning, we could break early once we find missing. That's done.
Now, one nuance: In Python, list of booleans initially are False. However, if we use list comprehension [False]*size, it's fine. But for very large size? 17576 is fine.
Now, but we need to be careful: For length 3, we should compute base = 26*26 = 676.
Now, I'll produce final answer.
But wait: The problem statement says "The sum of n over all test cases will not exceed 1000." So it's indeed small. So even if we use sets and generate all strings of length up to 3 in lexicographic order, it's fine. But we'll stick with boolean arrays.
Now, I'll produce final code with proper input reading.
One more check: The example input formatting shows blank lines? The sample input shows:
3
28
qaabzwsxedcrfvtgbyhnujmiklop
13
cleanairactbd
10
aannttoonn
No blank lines. So our split works.
Now, I'll write final solution.
But hold on: There is a nuance: The string can be up to 1000, and we are using ord() repeatedly. That's fine.
Now, I will write the solution in a clear way.
One more edge: What if n is very large (1000) and we need length 3? The present3 array of size 17576 is okay, but scanning 17576 indices in Python might be a bit slower but acceptable. However, we can optimize by using bytearray for faster allocation and scanning? But not necessary.
But let's consider the possibility of a test where all length-2 strings are present, which implies n>=677. Given total sum n=1000, there can be at most one such test (since 677+something else might exceed 1000). So scanning 17576 for that one test is trivial.
Thus final code as above.
Now, I'll produce final answer.
But wait: There is a subtlety: The definition of MEX: "shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX." So we need to output that string. Our algorithm for each length finds the lexicographically smallest missing of that length. Since we start from length 1, that's the answer. Good.
Now, let's test more:
Case: n=677, s is de Bruijn sequence of order 2 (all pairs). We need to verify that our algorithm for length 2 will find no missing (present2 all true). Then go to length 3. Then we will output the smallest missing triple. But is it possible that there is a missing string of length 2? No, because we checked all and they are present. So fine.
Now, what about n=676? Could all 676 pairs be present in a string of length 676? For a cyclic de Bruijn sequence, the linear version of length 676 would contain all pairs if we consider the cyclic string? But for linear, to contain all 676 distinct pairs, you need at least 677 characters because you need 676 overlapping pairs from a sequence of length L yields L-1 substrings. So L-1 = 676 => L=677. So it's impossible to have all 676 pairs in a string of length 676. Because number of substrings length 2 is n-1. If n=676, max distinct is 675. So cannot have all 676. So length 2 missing will be found before L=3. So our algorithm won't go to length 3 for n < 677. So only if n >= 677 and also actually contains all 676 distinct pairs, we go to length 3. But it's possible that n >= 677 but still does not contain all pairs; then length 2 missing, we output that. So only if string is specifically constructed to contain all pairs (like de Bruijn) will we need length 3.
Thus good.
Now, confirm that the boolean array for length 2 is correct: There are 26*26=676 possible pairs. We mark those that appear. Then we scan from 0 to 675. That's fine.
Now, also need to ensure that for length 2, when scanning, we output two characters, but we must ensure we format as string.
Now, final code.
But before finalizing, consider using sys.stdout.write and join for speed, though not necessary.
Now, one more nuance: The problem says "the sum of n over all test cases will not exceed 1000." However, t can be up to 1000. So there could be many test cases with n=1. Our code will allocate present1 each time (size 26) and iterate over characters. That's fine.
Now, we can also optimize by early exiting when we find answer. Already done.
Now, produce final answer.
Given that this is a typical Codeforces problem (probably from Round #1730? Actually I recall a problem about MEX of string). It's usually solved by checking up to length 3.
Now, I'll finalize.
But let's double-check the sample:
Input:
3
28
qaabzwsxedcrfvtgbyhnujmiklop
13
cleanairactbd
10
aannttoonn
Our code:
Test 1: all letters present? present1: all true? Should be because string contains all letters? Let's verify: The string includes 'q','a','b','z','w','s','x','e','d','c','r','f','v','t','g','y','h','n','u','j','m','i','k','l','o','p'. Also includes '? Actually need all 26: a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z. Check: a present, b present, c present? index 10 'c', d present? index 9 'd', e present? index 8 'e', f present? index 12 'f', g present? index 15 'g', h present? index 18 'h', i present? index 23 'i', j present? index 21 'j', k present? index 24 'k', l present? index 25 'l', m present? index 22 'm', n present? index 19 'n', o present? index 26 'o', p present? index 27 'p', q present? index 0 'q', r present? index 11 'r', s present? index 6 's', t present? index 14 't', u present? index 20 'u', v present? index 13 'v', w present? index 5 'w', x present? index 7 'x', y present? index 17 'y', z present? index 4 'z'. So indeed all 26. So go length 2. present2 computed as above. scanning idx 0: "aa" present, idx1: "ab" present, idx2: "ac" missing -> output "ac". matches.
Test 2: string "cleanairactbd". Check letters: c,l,e,a,n,a,i,r,a,c,t,b,d. That's a,c,d,e,i,l,n,r,t,b? Actually let's list unique: c, l, e, a, n, i, r, t, b, d. That's 10 letters. Missing letters from a..z: f is smallest. So output "f". matches.
Test 3: "aannttoonn". letters: a,n,t,o. Missing b is smallest. Output "b". matches.
Thus correct.
Now, we should also consider an edge: if the string contains all 26 letters and also all 676 pairs, then we go to length 3. Let's manually test with a small example but with reduced alphabet to verify scanning works. For instance, suppose alphabet is only 2 letters for testing, but actual problem uses 26. We can't reduce but can think. For alphabet size 2, possible pairs: aa, ab, ba, bb (4). If string contains all 4 pairs, we would go to length 3. The number of possible triples is 8. Our algorithm would output the smallest missing triple. For example, if string is "aabbaa" (but that's length 6, does it contain all pairs? Let's see: "aa", "ab", "bb", "ba"? Actually "aabbaa": substrings length2: (0)aa, (1)ab, (2)bb, (3)ba, (4)aa. So all 4 pairs present. Then triples: aab, abb, bba, baa, aab? So present: aab, abb, bba, baa. Missing: aaa, aba, bab, bbb. Lex smallest missing is "aaa". So output "aaa". Our algorithm would compute present3 array size 8, mark indices for aab etc. Then scan idx 0: "aaa" missing, output. Works.
Now, if "aaa" appears as well, then "aab" might be missing? But if all triples appear, need length 4. But with n= something, but not possible if n small. So fine.
Now, think about time: scanning 17576 indices is not too much. However, if we have many test cases each requiring length 3, but sum n is 1000, so at most one such test case can have n≥677, maybe two if each around 500? Actually two tests of 500 each sum to 1000, but each would be <677 so wouldn't go to length 3. So at most one test can reach length 3. So scanning 17576 once is fine.
Now, final code.
But there is one more nuance: The definition of substring includes substrings of length 0? The problem says "empty substring does NOT count as a valid MEX". So we skip length 0. Our length 1 is the first.
Now, all good.
Now, I'll produce final solution.
But before finalizing, consider potential optimization: Instead of scanning whole boolean array, we could compute missing using other methods. But not needed.
Now, final code:
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
s = next(it)
# length 1
seen = [False] * 26
for ch in s:
seen[ord(ch) - 97] = True
for i in range(26):
if not seen[i]:
out_lines.append(chr(i + 97))
break
else:
# length 2
seen2 = [False] * 676
for i in range(n - 1):
idx = (ord(s[i]) - 97) * 26 + (ord(s[i + 1]) - 97)
seen2[idx] = True
for idx in range(676):
if not seen2[idx]:
out_lines.append(chr(idx // 26 + 97) + chr(idx % 26 + 97))
break
else:
# length 3
seen3 = [False] * (26 * 26 * 26)
base = 26 * 26
for i in range(n - 2):
idx = (ord(s[i]) - 97) * base + (ord(s[i + 1]) - 97) * 26 + (ord(s[i + 2]) - 97)
seen3[idx] = True
for idx in range(26 * 26 * 26):
if not seen3[idx]:
c1 = idx // base
r = idx % base
c2 = r // 26
c3 = r % 26
out_lines.append(chr(c1 + 97) + chr(c2 + 97) + chr(c3 + 97))
break
sys.stdout.write("\n".join(out_lines))
if __name__ == "__main__":
main()
Now, I'll double-check: In length 3, base = 2626 = 676. The expression: (ord(s[i]) - 97) * base + (ord(s[i+1]) - 97) * 26 + (ord(s[i+2]) - 97). That's correct. Then scanning idx from 0 to 2626*26-1 = 17575.
Now, maybe we should use a variable for 26^3 to avoid magic number: 26**3 = 17576, but we can compute.
Now, check: For length 3, if n-2 is 0 (n<3) we wouldn't go there because we already passed length 1 and 2 only if all letters present, which implies n>=26. So n>=26, so n-2 >= 24, so loop fine.
Now, potential pitfall: The second 'else' attached to 'for' loop for length 2 will execute only if the for loop completes without break. That's when all 676 are present. So we go to length 3. That's correct.
Now, final answer.
But wait: For length 2, we are iterating over all indices 0..675. Could there be an issue with performance? Not.
Now, we can also precompute the list of all strings of length 1,2,3 in lex order to avoid recomputation? Not needed.
Now, final solution is ready.
Now, I'll produce final answer. ```python
import sys
def main():
data = sys.stdin.read().split()
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
s = next(it)
# ---- length 1 ----
seen1 = [False] * 26
for ch in s:
seen1[ord(ch) - 97] = True
for i in range(26):
if not seen1[i]:
out.append(chr(i + 97))
break
else:
# ---- length 2 ----
seen2 = [False] * 676 # 26 * 26
for i in range(n - 1):
idx = (ord(s[i]) - 97) * 26 + (ord(s[i+1]) - 97)
seen2[idx] = True
for idx in range(676):
if not seen2[idx]:
out.append(chr(idx // 26 + 97) + chr(idx % 26 + 97))
break
else:
# ---- length 3 ----
seen3 = [False] * (26 * 26 * 26) # 17576
base = 26 * 26
for i in range(n - 2):
idx = (ord(s[i]) - 97) * base + (ord(s[i+1]) - 97) * 26 + (ord(s[i+2]) - 97)
seen3[idx] = True
for idx in range(26 * 26 * 26):
if not seen3[idx]:
c1 = idx // base
r = idx % base
c2 = r // 26
c3 = r % 26
out.append(chr(c1 + 97) + chr(c2 + 97) + chr(c3 + 97))
break
sys.stdout.write("\n".join(out))
if name == "main":
main()