- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find ith element by rotating k times to right
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
Advertisements