Array ( [0] => [1] => questions [2] => Arrays [3] => Rotating-Array-by-k-times ) Arrays | Rotating Array by k times | THE INQUISITIVE





Rotating Array by k times

LEVEL:Beginner

Description

Given list of elements and value K. You have to rotate in a clockwise the given array by k times and print the array. Note: You can try the same with anti-clockwise from your end. Observe the logic.

Input Format

First line contains a number N. Next line contains N integers separated by spaces. Next line contains value K.

Output Format

Print the resultant array.


Example 1:

Input
5
1 2 3 4 5
3
Output
4 5 1 2 3
Example 2:

Input
8
0 2 4 6 8 10 12 14
4
Output
8 10 12 14 0 2 4 6	
Example 3:

Input
10
1 4 7 10 13 16 19 22 25 28
2
Output
7 10 13 16 19 22 25 28 1 4

oops

Login to see Discussion




Approach

Approach 1: using brute force

Step-i) create copy of present array in temp
Step-ii) store the first element of temp in variable a
Step-iii) shift all the element of temp to left side by one place
Step-iv)assign a to the last index value of temp
Step-v) decrement k value
Step-vi) repeat ii, iii, iv and v until k>0
Step-vii) return the temp array (Note here string is used only for the sake of simplicity in printing and
avoid loops in the main method

Time Complexity: O(k*(n-1)) because we are performing n-1 shifts k times
Space Complexity: O(n)

Approach 2: using mod

Step-i) create copy of present array in temp
Step-ii) store the first element of temp in variable a
Step-iii) shift all the element of temp to left side by one place
Step-iv)assign a to the last index value of temp
Step-v) decrement k value
Step-vi) repeat ii, iii, iv and v until k%size >0
Step-vii) return the temp array (Note here string is used only for the sake of simplicity in printing and
avoid loops in the main method

Time Complexity: O(m*(n-1)) m = k%size
because we are performing n-1 shifts m times
Space Complexity: O(n)

Approach 3: Efficient solution

Step-i) reassign k value of k%size and copy array to the other array
Step-ii) reverse the elements of the array from index 0 to k-1
Step-iii) reverse the elements of array from index k to last index
Step-iv) now completely reverse the array
Step-v) return the array (Note here string is used only for the sake of simplicity in printing and
avoid loops in the main method

Time Complexity: O(n)
Space Complexity: O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution