MediumNo. 0189

Rotate Array — LeetCode 189 Python Solution

Topics
Array, Math, Two Pointers
On a study list
Top Interview 150
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

PythonSolution
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

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
2110Number of Smooth Descent Periods of a StockMedium
0048Rotate ImageMedium
0066Plus OneEasy
0204Count PrimesMedium
0335Self CrossingHard
0384Shuffle an ArrayMedium

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.

Free to download. Check it runs on your machine, then pick a plan.