Smallest String With Swaps in C++


Suppose we have 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. We can swap the characters at any pair of indices in the given pairs any number of times as we want. We have to find the lexicographically smallest string that s can be changed to after using the swaps. So if the input is like s = “dcab” and pairs = [[0,3], [1,2]], then the output will be “bacd”. Exchange s[0] and s[3], s = "bcad", then exchange s[1] and s[2], s = "bacd".

To solve this, we will follow these steps −

  • n := size of array, parent := make an array of size n, and fill this with -1

  • make a string called ret of size n and fill this with *

  • for i in range 0 to size of pairs

    • u := pairs[i, 0] and v := pairs[i, 1]

    • if parent of u is same as parent of v, then skip to next iteration

    • parent[parent of u] := parent of v

  • define an array arr1 of size n

  • for i in range 0 to n – 1: insert s[i] into arr[parent of i]

  • for i in range 0 to n – 1: sort arr[i] by reading the value from right

  • for i in range 0 to n – 1 −

    • ret[i] := last entry of arr1[parent of i]

    • delete the last node from arr1[parent of i]

Example (C++)

Let us see the following implementation to get a better understanding −

class Solution {
public:
   vector <int> parent;
   int getParent(int x){
      if(parent[x] == -1) return x;
      return parent[x] = getParent(parent[x]);
   }
   string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
      int n = s.size();
      parent = vector <int>(n, -1);
      string ret(n, '*');
      for(int i = 0; i < pairs.size(); i++){
         int u = pairs[i][0];
         int v = pairs[i][1];
         if(getParent(u) == getParent(v)) continue;
         parent[getParent(u)] = getParent(v);
      }
      vector < char > arr1[n];
      for(int i = 0; i < n; i++){
         arr1[getParent(i)].push_back(s[i]);
      }
      for(int i = 0; i < n; i++){
         sort(arr1[i].rbegin(), arr1[i].rend());
      }
      for(int i = 0; i < n; i++){
         ret[i] = arr1[getParent(i)].back();
         arr1[getParent(i)].pop_back();
      }
      return ret;
   }
};

Input

"dcab"
[[0,3],[1,2]]

Output

"bacd"

Updated on: 31-Mar-2020

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements