AlgoMaster Logo

Rotate Array

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute force approach involves rotating the array elements one step at a time. For each rotation, we move all the elements to their next position, simulating the rotation k times.

This matches the literal definition of “rotate right by k,” but it’s inefficient because elements are moved many times.

Steps:

Do this k times:

  • Save the last element.
  • Shift every element one step right.
  • Put the saved element at the front.

Code:

2. Extra Array

Intuition:

By using an additional array, you can directly place each element in its rotated position. This avoids costly movement within the original array but requires additional space for storing the results.

Steps:

  1. Create a new array to hold rotated elements.
  2. Calculate and place each element in its final position.
  3. Copy the result back into the original array.

Code:

3. Reverse the Array

Intuition:

The optimal solution utilizes array reversing. The underlying idea is that rotating an array is equivalent to reversing parts of the array.

Steps:

  1. Reverse the whole array.
  2. Reverse the first k elements.
  3. Reverse the remaining n-k elements.

Code:

Example Walkthrough:

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

0
1
1
2
2
3
3
4
4
5
5
6
6
7

Step 1: Reverse the whole array.

0
7
1
6
2
5
3
4
4
3
5
2
6
1

Step 2: Reverse the first 3 elements.

0
5
1
6
2
7
3
4
4
3
5
2
6
1

Step 3: Reverse the remaining 4 (7 - 3) elements.

0
5
1
6
2
7
3
1
4
2
5
3
6
4