Check if a string can be transformed to another by sorting substrings Last Updated : 27 Jun, 2021 Comments Improve Suggest changes Like Article Like Report 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. Choose a non-empty substring in str1 and sort it in-place lexicographically, to arrange the characters of the substring in non-decreasing order. Examples : Input: str1 = "hdecb", str2 = "cdheb"Output: YesExplanation:Sorting the substring "ec" in str1 modifies the string to "hdceb"Sorting the substring "hdc" in str1 modifies the string to "cdheb". Since, the modified 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 <bits/stdc++.h> 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[26]; 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<Integer> occur[] = new Vector[26]; for (int i = 0; i < occur.length; i++) occur[i] = new Vector<Integer>(); 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>[26]; 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[26]; 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 JavaScript <script> // JavaScript Program to implement // the above approach // Function to check if str1 can be // transformed to t by sorting substrings function canTransform(s, t) { var n = s.length; // Occur[i] stores the indices // of char ('a'+i) in string s var occur = Array.from(Array(26), ()=>new Array()); for (var x = 0; x < n; x++) { var ch = s[x].charCodeAt(0) - 'a'.charCodeAt(0); occur[ch].push(x); } // idx[i] stores the next available // index of char ('a'+i) in occur[i] var idx = Array(26).fill(0); var poss = true; for (var x = 0; x < n; x++) { var ch = t[x].charCodeAt(0) - 'a'.charCodeAt(0); // If this char is not available // anymore if (idx[ch] >= occur[ch].length) { // Conversion not possible poss = false; break; } for (var small = 0; small < ch; small++) { // If one of the smaller characters // is available and occurs before if (idx[small] < occur[small].length && occur[small][idx[small]] < occur[ch][idx[ch]]) { // Conversion not possible poss = false; break; } } idx[ch]++; } // Print the answer if (poss) { document.write( "Yes" ); } else { document.write( "No" ); } } // Driver Code var s, t; s = "hdecb"; t = "cdheb"; canTransform(s, t); </script> Output: Yes Time Complexity: O(N)Auxiliary Space: O(N) Comment More infoAdvertise with us Next Article Check if a string can be transformed to another by sorting substrings S shobhitgupta907 Follow Improve Article Tags : Strings Sorting Hash DSA strings +1 More Practice Tags : HashSortingStringsStrings Similar Reads Check if a string can be converted to another given string by removal of a substring Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print âYESâ. Otherwise, print âNOâ. Example: Input: S = âabcdefâ, T = âabcâ Output: YES Explana 7 min read Check if it is possible to transform one string to another Given two strings s1 and s2(all letters in uppercase). Check if it is possible to convert s1 to s2 by performing following operations. Make some lowercase letters uppercase. Delete all the lowercase letters. Examples: Input : s1 = daBcd s2 = ABC Output : yes Explanation : daBcd -> dABCd -> ABC 7 min read Check if a given string can be converted to another by given possible swaps Given two strings str1 and str2, the task is to check if a string str1 can be converted to string str2 by performing the following operations any number of times: Swap any two characters of str1.Swap all the occurrences of a character of str1 to all occurrences of any other distinct character of str 8 min read Check if the given string is shuffled substring of another string Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print "YES" if str1 is a substring in shuffled form of str2 else print "NO". Example Input: str1 = "onetwofour", str2 = "hellofourtwooneworld" Output: YES Explanation: str1 is substring in sh 15 min read Check if one string can be converted to another Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: Convert all the presence of a character by a different character. For example, if str = "abacd" and operation is to change character 'a' to 'k', then the resultant str 8 min read Longest Substring of A that can be changed to Substring of B in at most T cost Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. No 13 min read Transform the given String into two same Strings by removing at most one character Given a string S of length N where (N ? 1). The task is to check whether by removing at most one character from the given string it can be divided into two same sub-strings or not return YES or NO for possibilities. Examples: Input: N = 5, S = abzabOutput: YESExplanation: Character 'z' at index 3 ca 9 min read Sort a string according to the order defined by another string Given two strings (of lowercase letters), a pattern, and a string. The task is to sort strings according to the order defined by the pattern. It may be assumed that the pattern has all characters of the string and all characters in the pattern appear only once. Examples: Input : pat = "bca", str = " 9 min read Check if a string can be converted to another by swapping of adjacent characters of given type Given two strings str1 and str2 of size N consisting of only three characters A, B, and C, the task is to check whether the string str1 can be changed to str2 using the below operations: Replacing one occurrence of âBCâ with âCBâ i.e swap adjacent âBâ and âCâ.Replacing one occurrence of âCAâ with âA 7 min read Check if given string can be formed by two other strings or their permutations Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pairs from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" whi 13 min read Like