Rotate Array

Medium · Arrays & Hashing · Array · Math · Two Pointers

Problem

You are given an integer array nums and a non-negative integer k. Rotate the array to the right by k steps, in place: every element moves k positions to the right, and elements that run off the end wrap around to the front.

Return nothing; the array itself is checked after your function returns. k can be larger than the length of the array.

Examples

Input: nums = [10,20,30,40,50], k = 2
Output: [40,50,10,20,30]

The last two elements wrap around to the front.

Input: nums = [1,2,3], k = 4
Output: [3,1,2]

Rotating by 4 is the same as rotating by 4 % 3 = 1.

Input: nums = [-1,8], k = 0
Output: [-1,8]

Zero steps leave the array as it is.

Constraints

Approaches

Follow-up

There is a second O(1)-space method: cyclic replacement, which moves each element straight to (i + k) % n and follows the cycle it starts. How many cycles are there? (The answer is gcd(n, k).)

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…