![]() |
VOOZH | about |
Given an array arr[] of size N and a value K (-10^5<K<10^5), the task is to print the array rotated by K times to the right.
Examples:
Input: arr = {1, 3, 5, 7, 9}, K = 2
Output: 7 9 1 3 5
Explanation:
Rotating array 1 time right: 9, 1, 3, 5, 7
Rotating array 2 time right: 7, 9, 1, 3, 5Input: arr = {1, 2, 3, 4, 5}, K = -2
Output: 3 4 5 1 2
Explanation:
Rotating array -1 time right: 2, 3, 4, 5, 1
Rotating array -2 time right: 3, 4, 5, 1, 2
Naive Approach: The brute force approach to solve this problem is to use a temporary array to rotate the array K or -K times.
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach: The given problem can be solved by breaking the problem into the following parts:
3 4 5 1 2
Time Complexity: O(N)
Auxiliary Space: O(1)