Rotate Array

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Rotate Array

Approach

Use the triple-reverse technique: first reverse the entire array, then reverse the first k elements, then reverse the remaining elements. Each reverse uses two converging pointers. Normalize k by taking k mod n to handle cases where k exceeds array length.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Two Pointers (Triple Reverse)

Why It Works

Reversing the whole array puts elements in the right relative order but backwards. The two subsequent partial reverses flip each segment back to the correct order, completing the rotation.

Updated Feb 2026