AlgoInsight

DSA problem

Rotate Array

MediumArraysPattern: Array Reversaltop300AmazonMicrosoftGoogleAppleBloomberg

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

Rotating the array to the right means that each element moves k positions toward the end, and elements that fall off the end wrap around to the beginning. For example, rotating [1,2,3,4,5,6,7] by 3 steps produces [5,6,7,1,2,3,4].

The challenge is to perform the rotation in-place with O(1) extra space, without allocating a second array of the same size. Note that k may be larger than the array length, so it should be reduced modulo n first.

Examples

Example 1
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation: Rotate right by 1: [7,1,2,3,4,5,6]. Rotate right by 2: [6,7,1,2,3,4,5]. Rotate right by 3: [5,6,7,1,2,3,4].
Example 2
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: Rotate right by 1: [99,-1,-100,3]. Rotate right by 2: [3,99,-1,-100].
Example 3
Input: nums = [1,2], k = 3
Output: [2,1]
Explanation: Since k = 3 and n = 2, the effective rotation is 3 % 2 = 1 step.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraytwo-pointersmath

Browse all DSA problems