#C6847. Reverse a Substring to Sort the String
Reverse a Substring to Sort the String
Reverse a Substring to Sort the String
You are given a string s
consisting of lowercase letters. This string represents an arrangement of building heights. Your task is to determine a contiguous substring whose reversal will make the entire string sorted in non-decreasing order (i.e. in alphabetical order). The indices in the answer are 1-indexed. If the string is already sorted, the answer is (1, 1). If no such contiguous substring exists such that its reversal sorts the entire string, output -1.
Formally, let \( s = s_1s_2\ldots s_n \) and let \( t \) be the string obtained after reversing a substring \( s_l, s_{l+1}, \ldots, s_r \), i.e., \[ t = s_1s_2\ldots s_{l-1} \; (s_r s_{r-1}\ldots s_l) \; s_{r+1}s_{r+2}\ldots s_n \] Your objective is to determine indices \( l \) and \( r \) such that \( t \) is sorted in non-decreasing order. If the input string is already sorted, output \( l = 1 \) and \( r = 1 \). If no valid substring exists, output -1.
inputFormat
The input is read from standard input (STDIN) and is formatted as follows:
- The first line contains an integer \( T \), the number of test cases.
- The following \( T \) lines each contain a single string
s
.
Each string consists of lowercase letters.
outputFormat
For each test case, output one line on standard output (STDOUT):
- If a valid substring exists, print two space-separated integers \( l \) and \( r \) (the starting and ending indices, 1-indexed) representing the substring that when reversed sorts the string.
- If no valid substring exists, print -1.
5
abc
cba
bac
abcd
dcba
1 1
1 3
1 2
1 1
1 4
</p>