logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

189. Rotate Array

2 min read
On this pageApproach
ApproachComplexityCodeAnother Approach

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

Attention

There are at least three different ways to solve this problem. Try to do with O(1)\text{O}(1)O(1) space complexity.


# Approach

  • Reverse the all the nnn elements.
  • Reverse the first kkk elements.
  • Reverse the remaining n−kn-kn−k elements.

# Complexity

  • Time complexity : O(n)\text{O}(n)O(n)
    • We iterate the whole array only once
  • Space complexity : O(1)\text{O}(1)O(1)
    • No extra space is needed

# Code

public void rotate(int[] nums, int k) { 
	k %= nums.length; 
	reverse(nums, 0, nums.length - 1); 
	reverse(nums, 0, k - 1); 
	reverse(nums, k, nums.length - 1); 
}
 
public void reverse(int[] nums, int start, int end) { 
	while (start < end) { 
		int temp = nums[start]; 
		nums[start] = nums[end]; 
		nums[end] = temp; 
		start++; 
		end--; 
	} 
}

# Another Approach

# Intuition

  • If we double the array (e.g [1,2,3] will become [1,2,3,1,2,3])
    • Rotating array simply means start reading the array after skipping certain step.

# Approach

  • First create a new array double the size and copy the complete array twice onto it.
  • Amount of rotation can be simplified by minRotation=toatalRotationminRotation = toatalRotation%(arraySize)minRotation=toatalRotation
    • This is equivalent to toatalRotation=arraySize+arraySize+....+xtoatalRotation = arraySize + arraySize + .... + xtoatalRotation=arraySize+arraySize+....+x
  • Now rotating to right means start reading arraySizearraySizearraySize elements from index arraySize−minRotationarraySize - minRotationarraySize−minRotation

# Complexity

  • Time complexity : O(n)\text{O}(n)O(n)
    • We iterate the array twice only
  • Space complexity : O(n)\text{O}(n)O(n)
    • We create a new array double the size.

# Code

public void rotate(int[] nums, int k) { 
	int [] numsDoubled = new int[2*nums.length]; 
	for(int i = 0; i < nums.length; ++i) { 
		numsDoubled[i] = nums[i]; 
		numsDoubled[nums.length+i] = nums[i]; 
	} 
	k = k % nums.length; 
	for(int i = 0; i < nums.length; ++i) { 
		nums[i] = numsDoubled[ (nums.length - k) + i]; 
	} 
} 
←Previous122. Best Time to Buy and Sell Stock IINext→274. H-Index

On this page

ApproachComplexityCodeAnother Approach