I am trying to work through the following problem:
JavaScript
x
18
18
1
Given an array, rotate the array to the right by k steps, where k is non-negative.
2
3
Example 1:
4
5
Input: nums = [1,2,3,4,5,6,7], k = 3
6
Output: [5,6,7,1,2,3,4]
7
Explanation:
8
rotate 1 steps to the right: [7,1,2,3,4,5,6]
9
rotate 2 steps to the right: [6,7,1,2,3,4,5]
10
rotate 3 steps to the right: [5,6,7,1,2,3,4]
11
Example 2:
12
13
Input: nums = [-1,-100,3,99], k = 2
14
Output: [3,99,-1,-100]
15
Explanation:
16
rotate 1 steps to the right: [99,-1,-100,3]
17
rotate 2 steps to the right: [3,99,-1,-100]
18
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:
JavaScript
1
12
12
1
class Solution:
2
def rotate(self, nums: List[int], k: int) -> None:
3
"""
4
Do not return anything, modify nums in-place instead.
5
"""
6
nums = nums[::-1]
7
print('1st reverse', nums)
8
nums[:k] = nums[:k][::-1]
9
print('2nd reverse', nums)
10
nums[k:] = nums[k:][::-1]
11
print('final reverse', nums)
12
But this is my output. The list nums
stays the same:
JavaScript
1
15
15
1
Your input
2
[1,2,3,4,5,6,7]
3
3
4
5
stdout
6
1st reverse [7, 6, 5, 4, 3, 2, 1]
7
2nd reverse [5, 6, 7, 4, 3, 2, 1]
8
final reverse [5, 6, 7, 1, 2, 3, 4]
9
10
Output
11
[1,2,3,4,5,6,7]
12
13
Expected
14
[5,6,7,1,2,3,4]
15
Despite the fact that nums
is the correct order in my final reverse. Where am I going wrong?
Advertisement
Answer
This:
JavaScript
1
2
1
nums = nums[::-1]
2
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:
JavaScript
1
2
1
nums[:] = nums[::-1]
2