702712. Find Kth Rotation
Easy
Find Kth Rotation
Slug: rotation4723
Difficulty: Easy
Id: 702712
Topic Tags: Arrays, Searching, Data Structures, Algorithms
Company Tags: Flipkart, Amazon, ABCO
Summary
Given an array of size n and a value k, find the kth rotation in the array. The kth rotation is the element at index (k % n) - 1. For example, if the array is [1, 2, 3] and k = 2, the 2nd rotation would be the second element, which is 2.
Detailed Explanation
To solve this problem, we can simply calculate the kth rotation by using the modulo operator to ensure that the index stays within the bounds of the array. We then return the element at that index.
Here's a step-by-step breakdown of the solution:
- Calculate the kth rotation by taking the modulus of k with the size of the array (n).
- Subtract 1 from the result to get the correct index, since array indices start from 0.
- Return the element at the calculated index.
Time complexity: O(1) Space complexity: O(1)
Optimized Solutions
Java
public int findKthRotation(int[] arr, int k) {
return arr[(k % arr.length) - 1];
}