Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Method 1: Using pop() and insert()
We can simulate the rotation by moving the last element to the front k times ?
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))
10
Method 2: Using Slicing (Optimized)
Instead of rotating k times, we can calculate the final position directly using modular arithmetic ?
def solve_optimized(nums, k, i):
n = len(nums)
k = k % n # Handle k greater than array length
rotated = nums[-k:] + nums[:-k]
return rotated[i]
nums = [2, 7, 9, 8, 10]
k = 3
i = 2
print(solve_optimized(nums, k, i))
10
Method 3: Mathematical Approach
We can find the original index directly without actually rotating the array ?
def solve_mathematical(nums, k, i):
n = len(nums)
k = k % n # Handle k greater than array length
original_index = (i - k) % n
return nums[original_index]
nums = [2, 7, 9, 8, 10]
k = 3
i = 2
print(solve_mathematical(nums, k, i))
10
How It Works
For the mathematical approach:
- After k right rotations, element at original position (i - k) will be at position i
- We use modulo to handle negative indices and wrap around
- This gives us O(1) time complexity compared to O(k) for simulation
Comparison
| Method | Time Complexity | Space Complexity | Modifies Original? |
|---|---|---|---|
| pop() and insert() | O(k × n) | O(1) | Yes |
| Slicing | O(n) | O(n) | No |
| Mathematical | O(1) | O(1) | No |
Conclusion
The mathematical approach is most efficient with O(1) complexity. Use slicing for readability with medium-sized arrays, and avoid the simulation method for large k values.
