Rotate Array — LeetCode 189 Python Solution

MediumArrayMathTwo Pointers
Problem
#189
Reading time
2 min

The problem

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

Example

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]

Python solution

Python
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        def reverse(i: int, j: int):
            while i < j:
                nums[i], nums[j] = nums[j], nums[i]
                i, j = i + 1, j - 1

        n = len(nums)
        k %= n
        reverse(0, n - 1)
        reverse(0, k - 1)
        reverse(k, n - 1)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 189. Rotate Array is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 189. Rotate Array?
LeetCode 189. Rotate Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 189. Rotate Array?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 189. Rotate Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 189. Rotate Array cover?
LeetCode 189. Rotate Array is tagged Array, Math and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview