Related Articles
Sort a string lexicographically by reversing a substring
• Last Updated : 14 May, 2021

Given a string S consisting of N lowercase characters, the task is to find the starting and the ending indices ( 0-based indexing ) of the substring of the given string S that needed to be reversed to make the string S sorted. If it is not possible to sort the given string S by reversing any substring, then print “-1”.

Examples:

Input: S = “abcyxuz”
Output: 3 5
Explanation: Reversing the substring from indices [3, 5] modifies the string to “abcuxyz”, which is sorted.
Therefore, print 3 and 5.

Input: S = “GFG”
Output: 0 1

Naive Approach: The simplest approach to solve the given problem is to generate all possible substring of the given string S and if there exists any substring such reversing it makes the string sorted, then print the indices of that substrings. Otherwise, print “-1”.

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized based on the observation that to sort the string by only reversing one substring, the original string must be in one of the following formats:

• Decreasing string
• Increasing substring + Decreasing substring
• Decreasing substring + Increasing substring
• Increasing substring + Decreasing substring + Increasing substring

Follow the steps below to solve the problem:

• Initialize two variables, say start and end as -1, that stores the starting and ending indices of the substring to be reversed respectively.
• Initialize a variable, say flag as 1, that stores if it is possible to sort the string or not.
• Iterate over the range [1, N] and perform the following operations:
• If the characters S[i] is less than characters S[i – 1] then find the index of the right boundary of the decreasing substring starting from the index (i – 1) and store it in end.
• Check if reversing the substring S[i – 1, end] makes the string sorted or not. If found to be false then print “-1” and return. Otherwise, mark the flag as false.
• After completing the above steps update the value of i with the right boundary of the substring.
• If the characters S[i] is less than characters S[i – 1] and the flag is false, then print “-1” and return.
• If the start is equal to -1, then update the value of start and end as 1.
• After completing the above steps, print the value of start and end as the result.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find the substring``// in S required to be reversed``bool` `adjust(string& S, ``int``& i,``            ``int``& start, ``int``& end)``{``    ``// Stores the size of the string``    ``int` `N = S.length();` `    ``// Stores the starting point``    ``// of the substring``    ``start = i - 1;` `    ``// Iterate over the string S``    ``// while i < N``    ``while` `(i < N && S[i] < S[i - 1]) {` `        ``// Increment the value of i``        ``i++;``    ``}` `    ``// Stores the ending index of``    ``// the substring``    ``end = i - 1;` `    ``// If start <= 0 or i >= N``    ``if` `(start <= 0 && i >= N)``        ``return` `true``;` `    ``// If start >= 1 and i <= N``    ``if` `(start >= 1 && i <= N) {` `        ``// Return the boolean value``        ``return` `(S[end] >= S[start - 1]``                ``&& S[start] <= S[i]);``    ``}` `    ``// If start >= 1``    ``if` `(start >= 1) {` `        ``// Return the boolean value``        ``return` `S[end] >= S[start - 1];``    ``}` `    ``// If i < N``    ``if` `(i < N) {` `        ``// Return true if S[start]``        ``// is less than or equal to``        ``// S[i]``        ``return` `S[start] <= S[i];``    ``}` `    ``// Otherwise``    ``return` `false``;``}` `// Function to check if it is possible``// to sort the string or not``void` `isPossible(string& S, ``int` `N)``{``    ``// Stores the starting and the``    ``// ending index of substring``    ``int` `start = -1, end = -1;` `    ``// Stores whether it is possible``    ``// to sort the substring``    ``bool` `flag = ``true``;` `    ``// Traverse the range [1, N]``    ``for` `(``int` `i = 1; i < N; i++) {` `        ``// If S[i] is less than S[i-1]``        ``if` `(S[i] < S[i - 1]) {` `            ``// If flag stores true``            ``if` `(flag) {` `                ``// If adjust(S, i, start,``                ``// end) return false``                ``if` `(adjust(S, i, start, end)``                    ``== ``false``) {` `                    ``// Print -1``                    ``cout << -1 << endl;``                    ``return``;``                ``}` `                ``// Unset the flag``                ``flag = ``false``;``            ``}` `            ``// Otherwise``            ``else` `{` `                ``// Print -1``                ``cout << -1 << endl;``                ``return``;``            ``}``        ``}``    ``}` `    ``// If start is equal to -1``    ``if` `(start == -1) {``        ``// Update start and end``        ``start = end = 1;``    ``}` `    ``// Print the value of start``    ``// and end``    ``cout << start << ``" "``         ``<< end << ``"\n"``;``}` `// Driver Code``int` `main()``{``    ``string S = ``"abcyxuz"``;``    ``int` `N = S.length();``    ``isPossible(S, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``import` `java.lang.*;` `class` `GFG{``    ` `static` `int` `i, start, end;` `// Function to find the substring``// in S required to be reversed``static` `boolean` `adjust(String S)``{``    ` `    ``// Stores the size of the string``    ``int` `N = S.length();` `    ``// Stores the starting point``    ``// of the substring``    ``start = i - ``1``;` `    ``// Iterate over the string S``    ``// while i < N``    ``while` `(i < N && S.charAt(i) < ``                    ``S.charAt(i - ``1``))``    ``{``        ` `        ``// Increment the value of i``        ``i++;``    ``}` `    ``// Stores the ending index of``    ``// the substring``    ``end = i - ``1``;` `    ``// If start <= 0 or i >= N``    ``if` `(start <= ``0` `&& i >= N)``        ``return` `true``;` `    ``// If start >= 1 and i <= N``    ``if` `(start >= ``1` `&& i <= N)``    ``{``        ` `        ``// Return the boolean value``        ``return` `(S.charAt(end) >= S.charAt(start - ``1``) &&``                ``S.charAt(start) <= S.charAt(i));``    ``}` `    ``// If start >= 1``    ``if` `(start >= ``1``)``    ``{``        ` `        ``// Return the boolean value``        ``return` `S.charAt(end) >= S.charAt(start - ``1``);``    ``}` `    ``// If i < N``    ``if` `(i < N)``    ``{``        ` `        ``// Return true if S[start]``        ``// is less than or equal to``        ``// S[i]``        ``return` `S.charAt(start) <= S.charAt(i);``    ``}` `    ``// Otherwise``    ``return` `false``;``}` `// Function to check if it is possible``// to sort the string or not``static` `void` `isPossible(String S, ``int` `N)``{``    ` `    ``// Stores the starting and the``    ``// ending index of substring``    ``start = -``1``; end = -``1``;` `    ``// Stores whether it is possible``    ``// to sort the substring``    ``boolean` `flag = ``true``;` `    ``// Traverse the range [1, N]``    ``for``(i = ``1``; i < N; i++)``    ``{``        ` `        ``// If S[i] is less than S[i-1]``        ``if` `(S.charAt(i) < S.charAt(i - ``1``))``        ``{``            ` `            ``// If flag stores true``            ``if` `(flag)``            ``{``                ` `                ``// If adjust(S, i, start,``                ``// end) return false``                ``if` `(adjust(S) == ``false``)``                ``{``                    ` `                    ``// Print -1``                    ``System.out.println(-``1``);``                    ``return``;``                ``}` `                ``// Unset the flag``                ``flag = ``false``;``            ``}` `            ``// Otherwise``            ``else``            ``{``                ` `                ``// Print -1``                ``System.out.println(-``1``);``                ``return``;``            ``}``        ``}``    ``}` `    ``// If start is equal to -1``    ``if` `(start == -``1``)``    ``{``        ` `        ``// Update start and end``        ``start = end = ``1``;``    ``}` `    ``// Print the value of start``   ``System.out.println(start + ``" "` `+ end);``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``String S = ``"abcyxuz"``;``    ``int` `N = S.length();``    ``isPossible(S, N);``}``}` `// This code is contributed by offbeat`

## Python3

 `# Python3 program for the above approach` `# Function to find the substring``# in S required to be reversed``def` `adjust(S, i, start, end):``  ` `    ``# Stores the size of the string``    ``N ``=` `len``(S)` `    ``# Stores the starting point``    ``# of the substring``    ``start ``=` `i ``-` `1` `    ``# Iterate over the string S``    ``# while i < N``    ``while` `(i < N ``and` `S[i] < S[i ``-` `1``]):``        ` `        ``# Increment the value of i``        ``i ``+``=` `1` `    ``# Stores the ending index of``    ``# the substring``    ``end ``=` `i ``-` `1` `    ``# If start <= 0 or i >= N``    ``if` `(start <``=` `0` `and` `i >``=` `N):``        ``return` `True``,start,i,end` `    ``# If start >= 1 and i <= N``    ``if` `(start >``=` `1` `and` `i <``=` `N):` `        ``# Return the boolean value``        ``return` `(S[end] >``=` `S[start ``-` `1``] ``and` `S[start] <``=` `S[i]),start,i,end` `    ``# If start >= 1``    ``if` `(start >``=` `1``):``      ` `        ``# Return the boolean value``        ``return` `(S[end] >``=` `S[start ``-` `1``]),start,i,end` `    ``# If i < N``    ``if` `(i < N):` `        ``# Return true if S[start]``        ``# is less than or equal to``        ``# S[i]``        ``return` `(S[start] <``=` `S[i]),start,i,end` `    ``# Otherwise``    ``return` `False``,start,i,end` `# Function to check if it is possible``# to sort the string or not``def` `isPossible(S, N):``  ` `    ``# global start,end,i``    ``# Stores the starting and the``    ``# ending index of substring``    ``start, end ``=` `-``1``, ``-``1` `    ``# Stores whether it is possible``    ``# to sort the substring``    ``flag ``=` `True` `    ``# Traverse the range [1, N]``    ``i ``=` `1``    ``while` `i < N:``      ` `        ``# If S[i] is less than S[i-1]``        ``if` `(S[i] < S[i ``-` `1``]):` `            ``# If flag stores true``            ``if` `(flag):` `                ``# If adjust(S, i, start,``                ``# end) return false``                ``f, start, i, end ``=` `adjust(S, i, start, end)``                ``if` `(f``=``=` `False``):``                    ``# Pr-1``                    ``print``(``-``1``)``                    ``return` `                ``# Unset the flag``                ``flag ``=` `False``            ``# Otherwise``            ``else``:` `                ``# Pr-1``                ``print``(``-``1``)``                ``return``        ``i ``+``=` `1`        `    ``# If start is equal to -1``    ``if` `(start ``=``=` `-``1``):``        ``# Update start and end``        ``start, end ``=` `1``, ``1` `    ``# Prthe value of start``    ``# and end``    ``print``(start, end)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``S ``=` `"abcyxuz"``    ``N ``=` `len``(S)``    ``isPossible(S, N)` `    ``# This code is contributed by mohit kumar 29.`
Output:
`3 5`

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

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up