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
ArraysBoyer-Moore Majority Vote AlgorithmKadane’s AlgorithmTriple Reverse algorithm aka Reversal Algorithm
Cycle detectionDijkstraDisjoint Set UnionGraphTopological SortTraversal algorithmsTree Traversal
Binary HeapBinomial HeapHeap
Cycle DetectionLinked ListSorting
Finding the majority elementRotate array by K steps
Finding If Number is PrimeGCD of two numbersPerforming ExponentiationPrime NumbersRandomising Data
3. Max Consecutive OnesHoare'S Partition SchemeLomuto Partition Scheme
DequesPriority QueueQueue
The Binary Search Master GuideThe Rotated Sorted Array Master Guide
Bubble SortCounting SortInsertion SortMerge SortPigeon Hole SortQuick SortSelection Sort
Monotonic StackMonotonic StackStackReversing an ArrayStackTower of Hanoi
Binary Tree TraversalCentre of gravityDiameter of TreeShortest Path
Algorithmic Pattern/miscellaneous

Rotate array by K steps

1 min read
On this pageSimplify Rotation Amount
Simplify Rotation AmountRotationComplexityCode

# Simplify Rotation Amount

For an array of sized nnn instead of doing KKK rotation

K=n+n+n+...+xK = n + n + n + ... + xK=n+n+n+...+x

we can simply do K%nK\%nK%n rotation

x=K%nx = K\%nx=K%n

If we rotate KKKsteps to right we need to start reading the rotated array from the last K%nK\%nK%nelements.

If we rotate KKKsteps to left we need to start reading the rotated array after skipping K%nK\%nK%nelements from start

# Rotation

# 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--; 
	} 
}
←PreviousFinding the majority elementNext→Finding If Number is Prime

On this page

Simplify Rotation AmountRotationComplexityCode