189.rotate-array

In-place operations, runtime 76.67%

Xu LIANG
LeetCode Cracker
2 min readMar 31, 2019

--

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

Example 1:

Input: [1,2,3,4,5,6,7] and 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: [-1,-100,3,99] and 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]

Solution 1: pop and insert

This solution is very intuitive. We pop the last element and insert it at the beginning.

class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
i = 0
while i < k:
temp = nums.pop()
nums.insert(0, temp)
i += 1
# ✔ 34/34 cases passed (144 ms)
# ✔ Your runtime beats 8.28 % of python3 submissions
# ✔ Your memory usage beats 5.04 % of python3 submissions (13.4 MB)

Too slow! The insert operation is slow because it has to find the position to insert the element.

Solution 2: deque and appendleft

Deque is a list-like container with fast appends and pops on either end.

class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
from collections import deque
k = k % len(nums)
i = 0
d = deque(nums)
while i < k:
temp = d.pop()
d.appendleft(temp)
i += 1
nums[:] = d
# ✔ 34/34 cases passed (52 ms)
# ✔ Your runtime beats 76.67 % of python3 submissions
# ✔ Your memory usage beats 5.04 % of python3 submissions (13.4 MB)

--

--

Xu LIANG
LeetCode Cracker

I’m an engineer focusing on NLP and Data Science. I write stuff to repay the engineer community. You can find me on linkedin.com/in/xu-liang-99356891/