1611. Smallest After One Reversal
A playlist is stored as a singly linked list of track numbers in head. You may pick exactly one contiguous sublist and reverse it in place; a sublist of length 1 is allowed, which leaves the playlist unchanged. Choose the reversal that makes the whole sequence of values lexicographically smallest, comparing the first position where two results differ, and return the head of the resulting list. When several reversals give the same smallest sequence, any of them is fine because the output sequence is the same. The list has 1 to 2000 nodes with values from 0 to 10^9. Greedy idea: the reversal must start at the first index whose value is larger than the smallest value after it, and must end at an occurrence of that smallest value; compare the few candidate results. Time O(n^2), space O(n).
Example 1
- Input:
- head = [3,1,2]
- Output:
- [1,3,2]
- Explanation:
Reversing the first two nodes gives 1, 3, 2, which beats every other single reversal.
Example 2
- Input:
- head = [1,2,3,4]
- Output:
- [1,2,3,4]
- Explanation:
The list is already non-decreasing, so no reversal improves it.
Example 3
- Input:
- head = [5,2,3,2,9]
- Output:
- [2,3,2,5,9]
- Explanation:
Reversing from 5 through the second 2 gives 2, 3, 2, 5, 9, smaller than 2, 5, 3, 2, 9 from stopping at the first 2.
Constraints
1 ≤ length ≤ 2000
0 ≤ val ≤ 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^2)
- Space
- O(n)