Home > OS >  Reversing lists partially by reversing does not update the list
Reversing lists partially by reversing does not update the list

Time:04-16

I am trying to work through the following problem:

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

I am trying to solve this problem by reversing the list, then reversing the first k elements of the list and then reversing the remainder of the list. Like this:

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nums = nums[::-1]
        print('1st reverse', nums)
        nums[:k] = nums[:k][::-1]
        print('2nd reverse', nums)
        nums[k:] = nums[k:][::-1]
        print('final reverse', nums)

But this is my output. The list nums stays the same:

Your input
[1,2,3,4,5,6,7]
3

stdout
1st reverse [7, 6, 5, 4, 3, 2, 1]
2nd reverse [5, 6, 7, 4, 3, 2, 1]
final reverse [5, 6, 7, 1, 2, 3, 4]

Output
[1,2,3,4,5,6,7]

Expected
[5,6,7,1,2,3,4]

Despite the fact that nums is the correct order in my final reverse. Where am I going wrong?

CodePudding user response:

This:

nums = nums[::-1]

assigns nums to a new list. All of the operations you subsequently perform on nums are not on the list you originally pass into the function.

You're looking for:

nums[:] = nums[::-1]

CodePudding user response:

Originally thought it was working, but then reread the question more carefully.

To ensure the result is captured in the list passed as the argument, we can do this, for example:

def rotate(nums, k):
    temp = nums[::-1]
    temp[:k] = temp[:k][::-1]
    temp[k:] = temp[k:][::-1]
    nums[:] = temp

nums=[1,2,3,4,5,6,7]
rotate(nums, 3)
print(nums)

Output:

[5, 6, 7, 1, 2, 3, 4]
  • Related