DEV Community

Cover image for 1202. Smallest String With Swaps
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

1202. Smallest String With Swaps

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
  • s only contains lower case English letters.

Hint:

  1. Think of it as a graph problem.
  2. Consider the pairs as connected nodes in the graph, what can you do with a connected component of indices ?
  3. We can sort each connected component alone to get the lexicographically minimum string.

Similar Questions:

  1. 1722. Minimize Hamming Distance After Swap Operations
  2. 2076. Process Restricted Friend Requests
  3. 2231. Largest Number After Digit Swaps by Parity
  4. 2663. Lexicographically Smallest Beautiful String
  5. 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-1 as a node, and each pairs[i] = [a, b] as an undirected edge between nodes a and b.
  • 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 i from 0 to n-1), and
    • the list of characters located at those indices.
  • 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"
?>
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Union-Find setup:

    • Initialize parent[i] = i and rank[i] = 0.
    • For each pair [a, b], perform union(a, b).
    • Path compression in find() keeps operations nearly O(1) amortized.
    • Union by rank keeps the tree shallow.
  • Component grouping:

    • For each index i, find its root via find(i).
    • Append i to groups[root]['indices'] and s[i] to groups[root]['chars'].
    • Because we iterate i from 0 to n-1, indices are automatically in ascending order.
  • 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.
  • 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)) where p = 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).
  • Space Complexity:

    • parent and rank arrays: O(n).
    • groups storing indices and chars: O(n) total across all components.
    • answer array: 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!
Buy Me A Coffee

If you want more helpful content like this, feel free to follow me:

Top comments (0)