![]() |
VOOZH | about |
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::
Illustrations:
Below, you can find the representation of the string and the pairs of characters that can be swapped.
Next, we will construct a graph based on the relationships between pairs, which is depicted below.
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.
Below is the implementation of the above approach.
cxzebf
Time Complexity: O(N log N),
Auxiliary Space: O(N), where N is the length of the input String.