Flip a Stretch
Return a copy of nums in which the stretch from index i to index j, both included, is reversed. Everything outside the stretch stays where it is.
The classic way uses two positions: swap the items at i and j, then move both positions one step toward each other, and go on until they meet.
Example 1
nums [1,2,3,4,5]
i 1
j 3
returns [1,4,3,2,5]
The stretch [2, 3, 4] becomes [4, 3, 2]. The 1 and the 5 do not move.
Example 2
nums [1,2,3]
i 0
j 2
returns [3,2,1]
The stretch is the whole list.
Example 3
nums [7,8,9]
i 1
j 1
returns [7,8,9]
A stretch of one item is the same when reversed.
Constraints
1 <= len(nums) <= 300 <= nums[k] <= 990 <= i <= j < len(nums)
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Two pointers problems
- Fold and AddBeginner
- Lighten the ShelfBeginner
- Peel Matching EndsBeginner
- Sums of Every WindowBeginner
- Trim the ZerosBeginner
- Written BackwardsBeginner
- Zip Two Sorted ListsBeginner
- Best Window of Distinct NumbersEasy