1202. Smallest String With Swaps
Difficulty: Medium
Topics: Staff, Array, Hash Table, String, Depth-First Search, Breadth-First Search, Union-Find, Sorting, Weekly Contest 155
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
- Input: s = "dcab", pairs = [[0,3],[1,2]]
- Output: "bacd"
-
Explanation:
- Swap s[0] and s[3], s = "bcad"
- Swap s[1] and s[2], s = "bacd"
Example 2:
- Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
- Output: "abcd"
-
Explanation:
- Swap s[0] and s[3], s = "bcad"
- Swap s[0] and s[2], s = "acbd"
- Swap s[1] and s[2], s = "abcd"
Example 3:
- Input: s = "cba", pairs = [[0,1],[1,2]]
- Output: "abc"
-
Explanation:
- Swap s[0] and s[1], s = "bca"
- Swap s[1] and s[2], s = "bac"
- Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10⁵0 <= pairs.length <= 10⁵0 <= pairs[i][0], pairs[i][1] < s.length-
sonly contains lower case English letters.
Hint:
- Think of it as a graph problem.
- Consider the pairs as connected nodes in the graph, what can you do with a connected component of indices ?
- We can sort each connected component alone to get the lexicographically minimum string.
Similar Questions:
- 1722. Minimize Hamming Distance After Swap Operations
- 2076. Process Restricted Friend Requests
- 2231. Largest Number After Digit Swaps by Parity
- 2663. Lexicographically Smallest Beautiful String
- 2948. Make Lexicographically Smallest Array by Swapping Elements
Solution:
We solve this problem by recognizing that the pairs form a graph where indices are nodes and swaps are edges. All indices within a connected component can be freely permuted among themselves (since swaps can be applied any number of times). Therefore, for each connected component, we collect all characters at those indices and sort them ascending, then place them back in ascending index order. This yields the lexicographically smallest achievable string. We use Union-Find (Disjoint Set Union) with path compression and union by rank to efficiently compute connected components in near-linear time.
Approach
-
Model as a graph: Treat each index
0..n-1as a node, and eachpairs[i] = [a, b]as an undirected edge between nodesaandb. - Find connected components: Use Union-Find to merge all indices that are connected via swap pairs.
-
Group characters by component: For each connected component (keyed by its root), gather:
- the list of indices (in increasing order, since we iterate
ifrom0ton-1), and - the list of characters located at those indices.
- the list of indices (in increasing order, since we iterate
- Sort within each component: Sort the characters of each component ascending — this gives the smallest possible arrangement for those positions.
- Reassign sorted characters: Place the smallest character at the smallest index of the component, the next smallest at the next index, and so on.
- Return the result: Join the reassembled characters into a string.
Let's implement this solution in PHP: 1202. Smallest String With Swaps
<?php
/**
* @param String $s
* @param Integer[][] $pairs
* @return String
*/
function smallestStringWithSwaps(string $s, array $pairs): string
{
...
...
...
/**
* go to ./solution.php
*/
}
/**
* @param int $x
* @return int
*/
function find(int $x): int {
...
...
...
/**
* go to ./solution.php
*/
}
/**
* @param int $a
* @param int $b
* @return void
*/
function union(int $a, int $b): void {
...
...
...
/**
* go to ./solution.php
*/
}
// Test cases
echo smallestStringWithSwaps("dcab", [[0,3],[1,2]]) . "\n"; // Output: "bacd"
echo smallestStringWithSwaps("dcab", [[0,3],[1,2],[0,2]]) . "\n"; // Output: "abcd"
echo smallestStringWithSwaps("cba", [[0,1],[1,2]]) . "\n"; // Output: "abc"
?>
Explanation
-
Union-Find setup:
- Initialize
parent[i] = iandrank[i] = 0. - For each pair
[a, b], performunion(a, b). - Path compression in
find()keeps operations nearly O(1) amortized. - Union by rank keeps the tree shallow.
- Initialize
-
Component grouping:
- For each index
i, find its root viafind(i). - Append
itogroups[root]['indices']ands[i]togroups[root]['chars']. - Because we iterate
ifrom0ton-1,indicesare automatically in ascending order.
- For each index
-
Sorting & reconstructing:
- For each component,
sort($chars, SORT_STRING)gives the lexicographically smallest sequence of characters possible. - Assign
$chars[$k]to$answer[$indices[$k]]— smallest char goes to smallest index. - This is optimal because any permutation within a component is reachable, and putting sorted chars at sorted indices minimizes the string lexicographically.
- For each component,
Why this works: All indices in a connected component can be rearranged arbitrarily through a sequence of swaps. Lexicographic minimality is achieved by greedily assigning the smallest available character to the earliest position.
Complexity Analysis
-
Time Complexity:
- Union-Find operations (with path compression + union by rank):
O(α(n))per operation, whereαis the inverse Ackermann function (effectively constant). - Processing all pairs:
O(p · α(n))wherep = pairs.length. - Grouping indices and characters:
O(n). - Sorting characters within each component: total
O(n log n)in the worst case (single component). - Reconstructing the answer:
O(n). - Overall:
O(p · α(n) + n log n)≈O((n + p) · α(n) + n log n).
- Union-Find operations (with path compression + union by rank):
-
Space Complexity:
-
parentandrankarrays:O(n). -
groupsstoring indices and chars:O(n)total across all components. -
answerarray:O(n). - Overall:
O(n).
-
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:
Top comments (0)