189. Rotate Array (Leetcode || Solution || Java || Medium)

Palakkgoyal
2 min readOct 19, 2022

--

Given an array, 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?

SOLUTION:

We are going to rotate the array using the approach of [i +k%nums.length].

APPROACH:

Let’s say :

Given array nums = {1,2,3,4,5,6};

and we have given k = 3

So, we are going to set element of 0 index at k and element of 1st index at k+1 and so on.

Approach = [index of element + number of steps need to move(k) ] % length of array given]

Putting 0 index element at 3rd index: - (0 + 3) % 6 = 3;

temp array = {0,0,0,1,0,0}

Putting 1 index element at 4th index: - (1 + 3) % 6 = 4;

temp array = {0,0,0,1,2,0}

Putting 2 index element at 5th index: - (2 + 3) % 6 = 5;

temp array = {0,0,0,1,2,3}

Putting 3 index element at 0th index: - (3 + 3) % 6 = 0;

temp array = {4,0,0,1,2,3}

Putting 4 index element at 0th index: - (4 + 3) % 6 = 1;

temp array = {4,5,0,1,2,3}

Putting 5 index element at 0th index: - (5 + 3) % 6 = 2;

temp array = {4,5,6,1,2,3}

class Solution {
public void rotate(int[] nums, int k) {
int[] temp = new int[nums.length];//Creating new array to store rotated elements

for(int i = 0; i < nums.length; i++){//rotation
temp[(i + k) % nums.length] = nums[i];
}

for(int j = 0; j < nums.length; j++){//setting the elements of temp into nums
nums[j] = temp[j];
}
}
}

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet