189. Rotate Array
Given an integer array
nums, rotate the array to the right byksteps, wherekis 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]Constraints:
1 <= nums.length <= 105-231 <= nums[i] <= 231 - 10 <= k <= 105
Working method:
def rotate(self, nums: List[int], k: int) -> None:
k=k%len(nums)
nums[:]=nums[-k:]+nums[:-k]
Not working:
def rotate(self, nums: List[int], k: int) -> None:
extra = nums
nums = nums[-k:]
nums+=extra[:k+1]
print(nums)
- When you print it appears right, but the actual list isn't changed
The issue you're encountering is related to how Python handles variable assignments and references.
In Case 1:
extra = nums
nums = nums[-k:]
nums += extra[:k+1]
Here, when you assign extra = nums, both extra and nums reference the same list object. Later, when you modify nums, you are actually creating a new list object and assigning it to the variable nums. However, the original list referenced by extra remains unchanged.
In Case 2:
nums = nums[-k:] + nums[:-k]
This creates a new list by concatenating two slices of the original nums list, but it doesn't modify the original list in place. When you print nums after this operation, it looks correct, but if you inspect the original list that was passed to the function, it remains unchanged.
To modify the original list in place, you should use slice assignment, as shown in the corrected example in my previous response:
nums[:] = nums[-k:] + nums[:-k]
This modifies the content of the original list in place and ensures that changes are reflected outside the function. Always be cautious about assigning a new value to the variable holding the original list if you intend to modify the original list in place.