1361. One Reversal to Sorted
A parade line holds n distinct heights in the array nums. You may choose one contiguous stretch of the line and reverse it, once. Return [0, 0] if nums is already in ascending order. Otherwise, if reversing a single stretch nums[l..r] makes the whole line ascending, return [l, r] for the shortest such stretch, with l and r as 0-based inclusive indices. If no single reversal can sort the line, return [-1, -1]. The stretch must begin at the first position that is larger than its successor and end at the last position that is smaller than its predecessor. Aim for O(n) time and O(n) space.
Example 1
- Input:
- nums = [1,5,4,3,6]
- Output:
- [1,3]
- Explanation:
Reversing positions 1 to 3 turns 1, 5, 4, 3, 6 into 1, 3, 4, 5, 6.
Example 2
- Input:
- nums = [1,2,3]
- Output:
- [0,0]
- Explanation:
The line is already ascending, so the answer is [0, 0].
Example 3
- Input:
- nums = [3,1,2]
- Output:
- [-1,-1]
- Explanation:
The only descent is at the front, and reversing 3, 1 gives 1, 3, 2 which is still unsorted, so no single reversal works.
Constraints
1 ≤ n ≤ 1000
all values are distinct
-109 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)