Problem Description
Given a string s and a list of index pairs, each pair indicates two indices in s that can be swapped any number of times. The goal is to return the lexicographically smallest string possible by performing any series of swaps allowed by the given pairs.
Key Insights
- The index pairs form connections that can be modeled as a graph. Any indices that are connected (directly or indirectly) form a component in which characters can be arbitrarily rearranged.
- By finding all connected components, we can independently sort the characters from those indices and place them back in sorted order to achieve the smallest possible overall string.
- Approaches like Union Find, Depth-First Search, or Breadth-First Search can be used to identify these connected components.
Space and Time Complexity
Time Complexity: O(n log n + m * α(n))
Space Complexity: O(n)
Solution
The solution uses the Union Find (Disjoint Set Union) data structure:
- Use the union find structure to connect indices from the given pairs.
- Traverse through all indices and group them by their root parent (i.e., the connected component they belong to).
- For each group, extract the characters, sort them, and then reassign the sorted characters back to their corresponding positions in the string.
- Finally, join the characters to form the lexicographically smallest string possible.