Suppose we have an array nums, and a value k and another value i. We have to find the element at index i after rotating elements of nums, k number of times to the right.
So, if the input is like nums = [2,7,9,8,10] k = 3 i = 2, then the output will be 10 because after 3rd rotation array will be [9,8,10,2,7], so now the ith element will be nums[2] = 10.
To solve this, we will follow these steps −
- for r in range 0 to k, do
- delete last element from nums and insert that deleted element into nums at position 0
- return nums[i]
Example
Let us see the following implementation to get better understanding
def solve(nums, k, i): for r in range(k): nums.insert(0, nums.pop()) return nums[i] nums = [2,7,9,8,10] k = 3 i = 2 print(solve(nums, k, i))
Input
[2,7,9,8,10] , 3, 2
Output
10