Editorial
Let the missing student's name be .
If , the student immediately before in Class 6 must be , so . If , the student immediately after must be , so .
Therefore, for each name , it is sufficient to check the following two conditions:
- If , then .
- If , then .
The complete second-grade roster is already sorted. Collecting valid names in input order automatically produces the required sorted output.
The time complexity is per test case, and the space complexity is when the candidates are stored.
Solution written by GPT5.6