Let be the set of misplaced positions and let .
If , the answer is .
If , the answer is . Choose every misplaced position and add arbitrary fixed positions until exactly positions are chosen; one rearrangement can sort them all.
Now assume . Let and be the position sets chosen in two rearrangements. Since ,
Every position outside is never touched, so it must already be a fixed point.
If at least one fixed point exists, the answer is . One rearrangement is impossible because , while a fixed point can be kept outside both chosen sets so that the permutation can always be finished in two rearrangements.
Now suppose there is no fixed point. Then no position can lie outside , so the equality above forces . Thus and partition all positions. Every position in is touched only by the first rearrangement, so all of them must already be correct after that rearrangement.
Decompose the permutation into cycles. If contains only part of a cycle, at least one position in that part needs a value that remains in . Therefore must be a union of whole cycles. Conversely, if some cycle lengths sum to exactly , those cycles can be sorted in the first rearrangement and all remaining cycles in the second.
Hence, when there is no fixed point, two rearrangements are possible if and only if some subset of the cycle lengths sums to exactly . This is a standard subset-sum DP and can be checked in time.
If such a subset exists, the answer is ; otherwise it is . Two rearrangements are impossible by the condition above, while one preliminary rearrangement can create a fixed point, after which at most two more rearrangements are sufficient.
Therefore the answer is always one of . The time complexity is per test case and the memory complexity is .
Solution written by GPT5.6