VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lexicographically-smallest-string-by-pair-swapping/

⇱ Lexicographically smallest String by pair swapping - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographically smallest String by pair swapping

Last Updated : 23 Jul, 2025

Suppose you are given a string Str of length N and a set of Pairs ( i, j such that 0 <= i < j < N, 0 based indexing). Pair ā€œi, jā€ means that you can swap the ith and jth characters in the string any number of times. You have to output the lexicographically smallest string that can be produced by doing any number of swaps on the input string.

Examples:

Input: Str = zcxfbe Pairs = (0, 1), (0, 2), (3, 5)
Output: cxzebf
Explanation: First we will swap 0 and 2 char (new Str=xczfbe) then we will swap 0 and 1 char (new Str=cxzfbe) then we will swap 3 and 5 char (new Str=cxzebf).

Input: Str = dcab Pairs = (0, 3), (1, 2)
Output: bacd
Explanation: First we will swap 0 and 3 char (new Str=bcad) then we will swap 2 and 1 char (new Str=bacd).

Source: Directi Interview | Set 6 (On-Campus for Internship)

Efficient Approach: The approach is to find groups of characters that can be swapped together. We'll use a graph to connect characters that can be swapped within each group. Here are the steps to follow this approach::

  • Begin by creating N nodes to represent the string indexes.
  • Connect these nodes based on the given pairs of characters.
  • Group the connected nodes into disjoint sets, referred to as "Groups."
  • For each group, extract the characters from the input string corresponding to the group's indices.
  • Sort these extracted characters in lexicographical order.
  • Reconstruct the final rearranged string by placing the sorted characters back into their original positions according to the indices.

Illustrations:

Below, you can find the representation of the string and the pairs of characters that can be swapped.

šŸ‘ gfg-
String and pair representation.

Next, we will construct a graph based on the relationships between pairs, which is depicted below.

šŸ‘ gfg-(1)
Disjoint Graph and sorted Disjoint Graph Representation.

Now, we will arrange each disconnected subgraph in lexicographically sorted order, as shown above.

Subsequently, we will reconstruct the string using the lexicographically sorted graph.

šŸ‘ gfg-1
Final String Representation.

Below is the implementation of the above approach.


Output
cxzebf

Time Complexity: O(N log N),

Auxiliary Space: O(N), where N is the length of the input String.

Comment