My first instinct was to just simulate the swaps greedily and I wasted probably five minutes going down that path before realizing it doesn't work.
Model the index pairs as edges in an undirected graph where characters are nodes. Find connected components using union-find or DFS, then sort the characters within each component and place them in the smallest lexicographical order at the original positions.
Pro tip: Mention that the graph approach reduces the problem to sorting within components, achieving O(N log N) time, and discuss how to handle large inputs efficiently with union-find path compression.
Clarify that swaps can be performed any number of times, meaning characters can be rearranged freely within connected components of the swap graph.
Create an undirected graph where each index is a node and each swap pair is an edge. Use union-find or adjacency lists to represent it.
Identify all connected components using DFS, BFS, or union-find. Each component represents a set of indices whose characters can be permuted arbitrarily.
For each component, collect the characters at its indices, sort them, and assign the smallest characters to the smallest indices in the component.
Combine the assigned characters from all components to form the lexicographically smallest string.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.