#189MediumTwo Pointers

Rotate Array

Three reversals achieve an in-place rotation with no extra space.

MicrosoftBloombergAmazon

Problem Statement

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

Examples

Example 1

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

Example 2

Input:nums = [-1,-100,3,99], k = 2
Output:[3,99,-1,-100]

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -2³¹ ≤ nums[i] ≤ 2³¹-1
  • 0 ≤ k ≤ 10⁵

Solutions

1
Extra Array
TimeO(n)SpaceO(n)

Create a new array. Place each element at index (i + k) % n. Copy back.

Visual Animation
def rotate(nums: list[int], k: int) -> None:
    n = len(nums)
    k %= n
    temp = nums[:]
    for i in range(n):
        nums[(i + k) % n] = temp[i]

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Two Pointers to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems