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”.
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:
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.