Problem 253749 · easy · Level 02 Linear Data Structures

Reverse a Slice

arrays · slicing · reversal

Given a list nums and two indices i <= j, return a new list in which the elements from index i to index j (both inclusive) appear in reverse order while everything outside that range stays where it was.

Examples

Input:  nums = [8, 3, 6, 1, 9, 2], i = 1, j = 4
Output: [8, 9, 1, 6, 3, 2]
Explanation: the slice [3, 6, 1, 9] becomes [9, 1, 6, 3].

Input:  nums = [1, 2, 3], i = 0, j = 2
Output: [3, 2, 1]

Constraints

  • 1 <= len(nums) <= 10**5
  • 0 <= i <= j < len(nums)
  • Return a new list; do not modify nums. One test calls nums_after(nums, i, j), which runs your reverse_between, appends an item to the list you returned and then returns nums itself, so it must come back unchanged.
  • Target: O(n) time.

Goals

  • Combine slices to rebuild a list around a changed region
  • Handle inclusive index ranges correctly
  • Keep the untouched prefix and suffix intact
Starting Python…