VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-array-after-it-is-right-rotated-k-times-where-k-can-be-large-or-negative/

⇱ Print Array after it is right rotated K times where K can be large or negative - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Array after it is right rotated K times where K can be large or negative

Last Updated : 21 Sep, 2022

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, 5

Input: 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:

  1. Round up the value of K in range [0, N), using below steps:
    • If K is negative, first change it into positive, find the modulo with N, and then again change it to negative
    • If K is positive, just find the modulo with N
  2. Handle the case when K is negative. If K is negative, it means we need to rotate the array K times left, or -K times right.
  3. Next we can simply rotate the array K times by reversing subarrays. Below steps can be followed to solve the problem:
    • Reverse all the array elements from 1 to N -1
    • Reverse the array elements from 1 to K – 1
    • Reverse the array elements from K to N -1

 
 


Output
3 4 5 1 2 


 

Time Complexity: O(N)
Auxiliary Space: O(1)


 

Comment
Article Tags: