Treat each position as a vertex, and each allowed swap as an undirected edge. Edge swaps allow arbitrary rearrangement within a connected component. Sorting is therefore possible exactly when each component's current multiset equals its target multiset. Both positions have target value .
If or , the corresponding edge type is absent. Check isolated vertices too. Since values may repeat, comparing sums alone is insufficient. Total time for the full solution is . All index and frequency magnitudes are at most , so no arithmetic beyond signed 64-bit is required.
Solution written by GPT