0189. Rotate Array

0189. Rotate Array#

Problem#

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

Examples#

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 - 1
0 <= k <= 105

Followup#

  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.

  • Could you do it in-place with O(1) extra space?

Analysis#

  • what if k is greater than the length of the array?

Solution#

# A naive solution: append the rotated elements to the front of a list and then slice

def rotate(nums, k):
    for i in range(k):
        nums[:] = [nums[-1]] + nums[:-1]
    
    return nums

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

nums = [-1,-100,3,99]
k = 2
print(rotate(nums, k))

nums = [-1,-100,3,99]
k = 1
print(rotate(nums, k))

nums = [1]
k = 1
print(rotate(nums, k))

nums = [1, 2]
k = 3
print(rotate(nums, k))

# The above solution is too time-consuming using the for loop, which is O(n)
# To remove the for-loop, we can try:
def rotate(nums, k):
    k = k%len(nums)
    nums[:] = nums[-k:] + nums[:-k]
    
    return nums

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

nums = [-1,-100,3,99]
k = 2
print(rotate(nums, k))

nums = [-1,-100,3,99]
k = 1
print(rotate(nums, k))

nums = [1]
k = 1
print(rotate(nums, k))

nums = [1, 2]
k = 3
print(rotate(nums, k))
[5, 6, 7, 1, 2, 3, 4]
[3, 99, -1, -100]
[99, -1, -100, 3]
[1]
[2, 1]
[5, 6, 7, 1, 2, 3, 4]
[3, 99, -1, -100]
[99, -1, -100, 3]
[1]
[2, 1]
# Solution 2: Prepend a list in python is inefficient as list is a dynamic array. Dynamic array support append in O(1).
# The following is a in-place solution but needs O()

def rotate(nums, k):
    # reverse in O(n) time, O(1) space
    nums.reverse()
    # append the first k to the end in O(1) time
    for i in range(k):
        nums.append(nums[0])
        nums.pop(0)
    # reverse to output order
    nums.reverse()
 
# test
nums = [1,2,3,4,5,6,7]
k = 3
rotate(nums, k)
print(nums)

nums = [-1,-100,3,99]
k = 2
rotate(nums, k)
print(nums)

nums = [-1,-100,3,99]
k = 1
rotate(nums, k)
print(nums)

nums = [1]
k = 1
rotate(nums, k)
print(nums)

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