Talentd
FleetCode
Make and follow sheets.Sign in

Rotate Array solution and explanation

MediumArrayMathTwo Pointers5 min read45.3% acceptanceUpdated 9 Apr 2026
Rotate Array - Leetcode 189 - PythonNeetCode · 8:59 · 261K viewsWatch on YouTube
9 more videos on this problem
  1. Rotate Array - Leetcode 189 - PythonNeetCode · 8:59 · 261K views
  2. LeetCode Rotate Array Solution Explained - JavaNick White · 6:50 · 95K views
  3. Rotate Array | Leetcode 189 | Top 150 interview question seriesTechnosage · 11:41 · 77K views
  4. Rotate Array | LeetCode 189 (Reverse Method) | Coding Interview TutorialTerrible Whiteboard · 8:40 · 9K views
  5. Rotate Array | Shift 2D Grid | Smart Approach | Leetcode 189 | Leetcode 1260 | codestorywithMIKcodestorywithMIK · 20:18 · 5K views
  6. 189. Rotate Array Leetcode Problem | Solution with Explanation | DSA Problem SeriesCoding Blocks · 5:48 · 4K views
  7. LeetCode 189 | Rotate Array Solution Visually Explained | Top Interview 150 |ByteQuest · 2:18 · 4K views
  8. Rotate Array (Leetcode #189)Programmer Mitch · 12:46 · 4K views
  9. Rotate Array | LeetCode 189 (Pop / Unshift) | Coding Interview TutorialTerrible Whiteboard · 7:36 · 2K views
  10. Rotate Array - 189. LeetCode - JavaTeddy Smith · 8:44 · 1K views

The problem

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

Example 1:

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]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Constraints:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105

Follow up:

  • Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

Approach overview

Problem Overview: You’re given an integer array nums and an integer k. The task is to rotate the array to the right by k steps, meaning each element shifts right and wraps around to the beginning. For example, rotating [1,2,3,4,5,6,7] by 3 results in [5,6,7,1,2,3,4].

This problem tests your understanding of array manipulation and how to perform cyclic shifts efficiently. A key detail: when k is larger than the array length, only k % n rotations matter.

Approach 1: Using Additional Array (O(n) time, O(n) space)

Create a new array of the same size and place each element directly in its rotated position. First compute k = k % n so unnecessary rotations are avoided. Then iterate through the array and place each element at index (i + k) % n in the new array. After the pass finishes, copy the result back to the original array.

This approach works because the modulo operation naturally handles the wrap‑around from the end of the array back to the front. It’s easy to implement and very readable. The tradeoff is extra memory usage since an additional array of size n is required.

Approach 2: In-Place Reversal (O(n) time, O(1) space)

The optimal solution avoids extra memory by reversing sections of the array in place. The key insight: a right rotation can be expressed as three reversals. First reverse the entire array. Then reverse the first k elements. Finally reverse the remaining n - k elements.

Example: [1,2,3,4,5,6,7] with k = 3. Reverse all → [7,6,5,4,3,2,1]. Reverse first 3 → [5,6,7,4,3,2,1]. Reverse the rest → [5,6,7,1,2,3,4]. Each reversal uses two pointers moving from both ends toward the center, a common pattern in two pointers problems.

This method performs a constant number of passes over the array, giving O(n) time complexity and O(1) extra space. The math behind the rotation and modulo operation ties directly to concepts in math and cyclic indexing.

Recommended for interviews: Interviewers typically expect the in-place reversal approach. The additional array solution shows you understand the rotation mapping, but the reversal method demonstrates deeper algorithmic thinking and space optimization. Both run in linear time, but achieving O(1) space is the key differentiator.

Approach 1: Using Additional Array

This approach involves using an additional array to store the rotated order of elements. We calculate the new position for each element and place it in the new array. Finally, copy the elements of this new temporary array back into the original array.

def rotate(nums, k):
    n = len(nums)
    k = k % n
    rotated = nums[-k:] + nums[:-k]
    for i in range(n):
        nums[i] = rotated[i]

nums = [1,2,3,4,5,6,7]
k = 3
rotate(nums, k)
print(nums)
import java.util.Arrays;

public class RotateArray {
    public static void rotate(int[] nums, int k) {
        int n = nums.length;
        int[] rotated = new int[n];
        k = k % n;
        for (int i = 0; i < n; i++) {
            rotated[(i + k) % n] = nums[i];
        }
        System.arraycopy(rotated, 0, nums, 0, n);
    }

    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5,6,7};
        int k = 3;
        rotate(nums, k);
        System.out.println(Arrays.toString(nums));
    }
}
#include <iostream>
#include <vector>

void rotate(std::vector<int>& nums, int k) {
    int n = nums.size();
    std::vector<int> rotated(n);
    k = k % n;
    for (int i = 0; i < n; ++i) {
        rotated[(i + k) % n] = nums[i];
    }
    nums = rotated;
}

int main() {
    std::vector<int> nums = {1,2,3,4,5,6,7};
    int k = 3;
    rotate(nums, k);
    for(int num : nums) {
        std::cout << num << " ";
    }
    return 0;
}
function rotate(nums, k) {
    const n = nums.length;
    k = k % n;
    let rotated = nums.slice(-k).concat(nums.slice(0, n - k));
    for (let i = 0; i < n; i++) {
        nums[i] = rotated[i];
    }
}

let nums = [1,2,3,4,5,6,7];
let k = 3;
rotate(nums, k);
console.log(nums);
#include <stdio.h>

void rotate(int* nums, int numsSize, int k) {
    int rotated[numsSize];
    k = k % numsSize;
    for (int i = 0; i < numsSize; ++i) {
        rotated[(i + k) % numsSize] = nums[i];
    }
    for (int i = 0; i < numsSize; ++i) {
        nums[i] = rotated[i];
    }
}

int main() {
    int nums[] = {1,2,3,4,5,6,7};
    int k = 3;
    int numsSize = sizeof(nums)/sizeof(nums[0]);
    rotate(nums, numsSize, k);
    for(int i = 0; i < numsSize; i++) {
        printf("%d ", nums[i]);
    }
    return 0;
}
using System;

public class RotateArray {
    public static void Rotate(int[] nums, int k) {
        int n = nums.Length;
        int[] rotated = new int[n];
        k = k % n;
        for (int i = 0; i < n; i++) {
            rotated[(i + k) % n] = nums[i];
        }
        for (int i = 0; i < n; i++) {
            nums[i] = rotated[i];
        }
    }

    public static void Main(string[] args) {
        int[] nums = {1,2,3,4,5,6,7};
        int k = 3;
        Rotate(nums, k);
        Console.WriteLine(string.Join(",", nums));
    }
}

This Python solution uses slicing to create a new rotated list with the elements shifted k positions to the right and then copies the values back to the original list.

Complexity

Time Complexity: O(n). Space Complexity: O(n) as a new list of the same length is created.

Try this approach in the editor

Approach 2: In-Place Reversal

This approach involves reversing parts of the array to achieve the rotation without additional space. First, reverse the whole array, then reverse the first k elements, and finally reverse the remaining n-k elements. This series of reversals effectively performs the rotation in-place without needing extra storage.

def rotate(nums, k):
    def reverse(start, end):
        while start < end:
            nums[start], nums[end] = nums[end], nums[start]
            start, end = start + 1, end - 1

    n = len(nums)
    k %= n
    reverse(0, n - 1)
    reverse(0, k - 1)
    reverse(k, n - 1)

nums = [1,2,3,4,5,6,7]
k = 3
rotate(nums, k)
print(nums)
import java.util.Arrays;

class RotateArray {
    private static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }

    public static void rotate(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }

    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5,6,7};
        int k = 3;
        rotate(nums, k);
        System.out.println(Arrays.toString(nums));
    }
}
#include <iostream>
#include <vector>

void reverse(std::vector<int>& nums, int start, int end) {
    while (start < end) {
        std::swap(nums[start], nums[end]);
        start++;
        end--;
    }
}

void rotate(std::vector<int>& nums, int k) {
    int n = nums.size();
    k = k % n;
    reverse(nums, 0, n - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, n - 1);
}

int main() {
    std::vector<int> nums = {1,2,3,4,5,6,7};
    int k = 3;
    rotate(nums, k);
    for(int num : nums) {
        std::cout << num << " ";
    }
    return 0;
}
function rotate(nums, k) {
    function reverse(start, end) {
        while (start < end) {
            [nums[start], nums[end]] = [nums[end], nums[start]];
            start++;
            end--;
        }
    }

    const n = nums.length;
    k = k % n;
    reverse(0, n - 1);
    reverse(0, k - 1);
    reverse(k, n - 1);
}

let nums = [1,2,3,4,5,6,7];
let k = 3;
rotate(nums, k);
console.log(nums);
#include <stdio.h>

void reverse(int* nums, int start, int end) {
    while (start < end) {
        int temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;
        start++;
        end--;
    }
}

void rotate(int* nums, int numsSize, int k) {
    k = k % numsSize;
    reverse(nums, 0, numsSize - 1);
    reverse(nums, 0, k - 1);
    reverse(nums, k, numsSize - 1);
}

int main() {
    int nums[] = {1,2,3,4,5,6,7};
    int k = 3;
    int numsSize = sizeof(nums)/sizeof(nums[0]);
    rotate(nums, numsSize, k);
    for(int i = 0; i < numsSize; i++) {
        printf("%d ", nums[i]);
    }
    return 0;
}
using System;

public class RotateArray {
    private static void Reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }

    public static void Rotate(int[] nums, int k) {
        int n = nums.Length;
        k = k % n;
        Reverse(nums, 0, n - 1);
        Reverse(nums, 0, k - 1);
        Reverse(nums, k, n - 1);
    }

    public static void Main(string[] args) {
        int[] nums = {1,2,3,4,5,6,7};
        int k = 3;
        Rotate(nums, k);
        Console.WriteLine(string.Join(",", nums));
    }
}

In Python, the same strategy of reversing segments of the list in-place is applied. This saves space by sidestepping the need for any additional lists.

Complexity

Time Complexity: O(n). Space Complexity: O(1).

Try this approach in the editor

Approach 3: Reverse three times

We can assume the length of the array is n and calculate the actual number of steps needed by taking the module of k and n, which is k bmod n.

Next, let us reverse three times to get the final result:

  1. Reverse the entire array.
  2. Reverse the first k elements.
  3. Reverse the last n - k elements.

For example, for the array [1, 2, 3, 4, 5, 6, 7], k = 3, n = 7, k bmod n = 3.

  1. In the first reverse, reverse the entire array. We get [7, 6, 5, 4, 3, 2, 1].
  2. In the second reverse, reverse the first k elements. We get [5, 6, 7, 4, 3, 2, 1].
  3. In the third reverse, reverse the last n - k elements. We get [5, 6, 7, 1, 2, 3, 4], which is the final result.

The time complexity is O(n), where n is the length of the array. The space complexity is O(1).

/**
 Do not return anything, modify nums in-place instead.
 */
function rotate(nums: number[], k: number): void {
    const n: number = nums.length;
    k %= n;
    const reverse = (i: number, j: number): void => {
        for (; i < j; ++i, --j) {
            const t: number = nums[i];
            nums[i] = nums[j];
            nums[j] = t;
        }
    };
    reverse(0, n - 1);
    reverse(0, k - 1);
    reverse(k, n - 1);
}
func rotate(nums []int, k int) {
	n := len(nums)
	k %= n
	reverse := func(i, j int) {
		for ; i < j; i, j = i+1, j-1 {
			nums[i], nums[j] = nums[j], nums[i]
		}
	}
	reverse(0, n-1)
	reverse(0, k-1)
	reverse(k, n-1)
}
impl Solution {
    pub fn rotate(nums: &mut Vec<i32>, k: i32) {
        let n = nums.len();
        let k = (k as usize) % n;
        nums.reverse();
        nums[..k].reverse();
        nums[k..].reverse();
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using Additional Array

Time Complexity: O(n). Space Complexity: O(n) as a new list of the same length is created.

In-Place Reversal

Time Complexity: O(n). Space Complexity: O(1).

Reverse three times–

Complexity analysis

ApproachTimeSpaceWhen to Use
Using Additional ArrayO(n)O(n)Simple implementation and readability matter more than memory usage
In-Place ReversalO(n)O(1)Preferred in interviews or memory-constrained environments

Frequently asked questions

Is Rotate Array easy or hard?

Rotate Array is usually classified as a medium difficulty problem. The basic idea is simple, but recognizing the in-place reversal trick and implementing it correctly is what makes the problem more challenging.

How to solve Rotate Array in O(n)?

Use the reversal technique. First compute k % n, reverse the entire array, then reverse the first k elements, and finally reverse the remaining n - k elements. This transforms the array into the rotated order in linear time.

Rotate Array Python or Java solution?

Python and Java solutions typically implement either the extra array approach or the in-place reversal approach. The reversal version is preferred because it runs in O(n) time with O(1) additional space.

What is the best approach for Rotate Array?

The in-place reversal method is considered the best approach. It rotates the array in O(n) time using only O(1) extra space by reversing the entire array, then reversing the first k elements and the remaining elements.

Is Rotate Array asked at Google/Amazon/Meta?

Rotate Array is a common interview problem that appears in coding interviews at companies like Amazon, Google, and Meta. It tests array manipulation, modular arithmetic, and in-place algorithm design.

What data structure is used in Rotate Array?

The problem primarily uses arrays. Some implementations also rely on the two-pointer technique to reverse parts of the array efficiently while keeping the operation in-place.

What is the time complexity of Rotate Array?

Most optimal solutions run in O(n) time because each element must be moved or processed at least once. The in-place reversal technique performs three linear passes over the array but still remains O(n).

Comments

Now write it yourselfClose this page and solve Rotate Array in the editor, without looking.
Practise Rotate Array