# Check if a string can be transformed to another by sorting substrings

Given two strings str1 and str2, each of length N and consisting of lowercase English alphabets only, the task is to check if string str1 can be transformed to string str2 by performing the following operations any number of times.

Examples :

Input: str1 = “hdecb”, str2 = “cdheb”
Output: Yes
Explanation:
Sorting the substring “ec” in str1 modifies the string to “hdceb”
Sorting the substring “hdc” in str1 modifies the string to “cdheb”.
Since, the modifed string is same as str2, the answer is Yes.

Input: str1 = “abcdef”, str2 = “dacbfe”
Output: No

Approach: Follow the steps below to solve the problem:

• Observe that, in the string str1, if there are two characters str1[i] and str2[j] such that str1[i] < str1[j], then these characters can be swapped.
• In other words, it is possible to move a character freely to the left, until it encounters a smaller character. For example, “acdb” can be converted to either “acbd“, “abcd” as ‘b‘ can be moved freely to the left until ‘a‘ occurs.
• Therefore, check if it is possible to move the required characters to the left, to their respective positions in the string str2.
• Store the indices of every character of string str1 in an array.
• Traverse the string str2, and for each character, check if the same character in str1 can be shifted to that position or not.

Below is the implementation of the above approach:

## C++

 `// C++ Program to implement` `// the above approach`   `#include ` `using` `namespace` `std;`   `// Function to check if str1 can be` `// transformed to t by sorting substrings` `void` `canTransform(string& s, string& t)` `{` `    ``int` `n = s.length();`   `    ``// Occur[i] stores the indices` `    ``// of char ('a'+i) in string s` `    ``vector<``int``> occur;` `    ``for` `(``int` `x = 0; x < n; x++) {` `        ``char` `ch = s[x] - ``'a'``;` `        ``occur[ch].push_back(x);` `    ``}`   `    ``// idx[i] stores the next available` `    ``// index of char ('a'+i) in occur[i]` `    ``vector<``int``> idx(26, 0);` `    ``bool` `poss = ``true``;` `    ``for` `(``int` `x = 0; x < n; x++) {` `        ``char` `ch = t[x] - ``'a'``;`   `        ``// If this char is not available` `        ``// anymore` `        ``if` `(idx[ch] >= occur[ch].size()) {`   `            ``// Conversion not possible` `            ``poss = ``false``;` `            ``break``;` `        ``}` `        ``for` `(``int` `small = 0; small < ch; small++) {`   `            ``// If one of the smaller characters` `            ``// is available and occurs before` `            ``if` `(idx[small] < occur[small].size()` `                ``&& occur[small][idx[small]]` `                       ``< occur[ch][idx[ch]]) {`   `                ``// Conversion not possible` `                ``poss = ``false``;` `                ``break``;` `            ``}` `        ``}` `        ``idx[ch]++;` `    ``}`   `    ``// Print the answer` `    ``if` `(poss) {` `        ``cout << ``"Yes"` `<< endl;` `    ``}` `    ``else` `{` `        ``cout << ``"No"` `<< endl;` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``string s, t;`   `    ``s = ``"hdecb"``;` `    ``t = ``"cdheb"``;`   `    ``canTransform(s, t);` `    ``return` `0;` `}`

## Java

 `// Java Program to implement` `// the above approach` `import` `java.util.*;` `class` `GFG{`   `// Function to check if str1 ` `// can be transformed to t by ` `// sorting subStrings` `static` `void` `canTransform(String s, ` `                         ``String t)` `{` `  ``int` `n = s.length();`   `  ``// Occur[i] stores the indices` `  ``// of char ('a'+i) in String s` `  ``Vector occur[] = ``new` `Vector[``26``];` `  `  `  ``for` `(``int` `i = ``0``; i < occur.length; i++)` `    ``occur[i] = ``new` `Vector();` `  `  `  ``for` `(``int` `x = ``0``; x < n; x++) ` `  ``{` `    ``char` `ch = (``char``)(s.charAt(x) - ``'a'``);` `    ``occur[ch].add(x);` `  ``}`   `  ``// idx[i] stores the next available` `  ``// index of char ('a'+i) in occur[i]` `  ``int` `[]idx = ``new` `int``[``26``];` `  ``boolean` `poss = ``true``;` `  `  `  ``for` `(``int` `x = ``0``; x < n; x++) ` `  ``{` `    ``char` `ch = (``char``)(t.charAt(x) - ``'a'``);`   `    ``// If this char is ` `    ``// not available anymore` `    ``if` `(idx[ch] >= occur[ch].size()) ` `    ``{` `      ``// Conversion not possible` `      ``poss = ``false``;` `      ``break``;` `    ``}` `    ``for` `(``int` `small = ``0``; small < ch; small++) ` `    ``{` `      ``// If one of the smaller characters` `      ``// is available and occurs before` `      ``if` `(idx[small] < occur[small].size() && ` `          ``occur[small].get(idx[small]) < ` `          ``occur[ch].get(idx[ch])) ` `      ``{` `        ``// Conversion not possible` `        ``poss = ``false``;` `        ``break``;` `      ``}` `    ``}` `    ``idx[ch]++;` `  ``}`   `  ``// Print the answer` `  ``if` `(poss) ` `  ``{` `    ``System.out.print(``"Yes"` `+ ``"\n"``);` `  ``}` `  ``else` `  ``{` `    ``System.out.print(``"No"` `+ ``"\n"``);` `  ``}` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `  ``String s, t;` `  ``s = ``"hdecb"``;` `  ``t = ``"cdheb"``;` `  ``canTransform(s, t);` `}` `}`   `// This code is contributed by Rajput-Ji`

## Python3

 `# Python3 program to implement` `# the above approach`   `# Function to check if str1 can be` `# transformed to t by sorting substrings` `def` `canTransform(s, t):` `    `  `    ``n ``=` `len``(s)`   `    ``# Occur[i] stores the indices` `    ``# of ('a'+i) in string s` `    ``occur ``=` `[[] ``for` `i ``in` `range``(``26``)]` `    `  `    ``for` `x ``in` `range``(n):` `        ``ch ``=` `ord``(s[x]) ``-` `ord``(``'a'``)` `        ``occur[ch].append(x)`   `    ``# idx[i] stores the next available` `    ``# index of ('a'+i) in occur[i]` `    ``idx ``=` `[``0``] ``*` `(``26``)` `    ``poss ``=` `True` `    `  `    ``for` `x ``in` `range``(n):` `        ``ch ``=` `ord``(t[x]) ``-` `ord``(``'a'``)`   `        ``# If this is not available` `        ``# anymore` `        ``if` `(idx[ch] >``=` `len``(occur[ch])):`   `            ``# Conversion not possible` `            ``poss ``=` `False` `            ``break`   `        ``for` `small ``in` `range``(ch):`   `            ``# If one of the smaller characters` `            ``# is available and occurs before` `            ``if` `(idx[small] < ``len``(occur[small]) ``and` `                ``occur[small][idx[small]] < ` `                ``occur[ch][idx[ch]]):`   `                ``# Conversion not possible` `                ``poss ``=` `False` `                ``break` `            `  `        ``idx[ch] ``+``=` `1`   `    ``# Print the answer` `    ``if` `(poss):` `        ``print``(``"Yes"``)` `    ``else``:` `        ``print``(``"No"``)`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:`   `    ``s ``=` `"hdecb"` `    ``t ``=` `"cdheb"`   `    ``canTransform(s, t)`   `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to implement` `// the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG{`   `// Function to check if str1 ` `// can be transformed to t by ` `// sorting subStrings` `static` `void` `canTransform(String s, ` `                         ``String t)` `{` `  ``int` `n = s.Length;`   `  ``// Occur[i] stores the indices` `  ``// of char ('a'+i) in String s` `  ``List<``int``> []occur = ``new` `List<``int``>;` `  `  `  ``for``(``int` `i = 0; i < occur.Length; i++)` `    ``occur[i] = ``new` `List<``int``>();` `  `  `  ``for``(``int` `x = 0; x < n; x++) ` `  ``{` `    ``char` `ch = (``char``)(s[x] - ``'a'``);` `    ``occur[ch].Add(x);` `  ``}`   `  ``// idx[i] stores the next available` `  ``// index of char ('a'+i) in occur[i]` `  ``int` `[]idx = ``new` `int``;` `  ``bool` `poss = ``true``;` `  `  `  ``for``(``int` `x = 0; x < n; x++) ` `  ``{` `    ``char` `ch = (``char``)(t[x] - ``'a'``);`   `    ``// If this char is ` `    ``// not available anymore` `    ``if` `(idx[ch] >= occur[ch].Count) ` `    ``{` `        `  `      ``// Conversion not possible` `      ``poss = ``false``;` `      ``break``;` `    ``}` `    ``for``(``int` `small = 0; small < ch; small++) ` `    ``{` `        `  `      ``// If one of the smaller characters` `      ``// is available and occurs before` `      ``if` `(idx[small] < occur[small].Count && ` `            ``occur[small][idx[small]] < ` `            ``occur[ch][idx[ch]]) ` `      ``{` `          `  `        ``// Conversion not possible` `        ``poss = ``false``;` `        ``break``;` `      ``}` `    ``}` `    ``idx[ch]++;` `  ``}`   `  ``// Print the answer` `  ``if` `(poss) ` `  ``{` `    ``Console.Write(``"Yes"` `+ ``"\n"``);` `  ``}` `  ``else` `  ``{` `    ``Console.Write(``"No"` `+ ``"\n"``);` `  ``}` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `  ``String s, t;` `  ``s = ``"hdecb"``;` `  ``t = ``"cdheb"``;` `  `  `  ``canTransform(s, t);` `}` `}`   `// This code is contributed by Amit Katiyar`

Output:

```Yes

```

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.