Graph Theory37 sections · 1633 units
Open in Course

LeetCode 1202 Smallest String With Swaps - Algorithm

Sorting Components

1.1. Treat indices 00 to n1n-1 as nodes.

2.2. Union indices ii and jj if there is a swap pair [i, j].

3.3. Group characters by their index's leader.

4.4. For each group, sort the characters.

5.5. Rebuild the string: for each position, take the next smallest available character from its group.

Time: O(nlogn)O(n \log n) for sorting. DSU part is nearly linear.

Space complexity is O(n)O(n) for the data structures used.