I want to reduce execution time.

Given an array of size n and multiple values around which we need to left rotate the array.

Input:
First line consists of T test case. First line of every test case consists of N and K, N denoting number of elements of array and K denoting the number of places to shift. Second line of every test case consists of elements of array.

Output:
Single line output, print the rotated array.

Constraints:
1<=T<=100
1<=N<=10^4
1<=K<=10^4

Example:
Input:
1
5 14
1 3 5 7 9
Output:
9 1 3 5 7

Code :-
http://ide.geeksforgeeks.org/CooMFU

Note:-Code was not getting pasted properly so code url is attached.

Please suggest ways for reducing execution time.

just double the array into 1 3 5 7 9 1 3 5 7 9 , then since its 14 places do 14%5=4 , so print from 4th elemnt to 4+5=9th elemnt

and i c please donot use /t , since in the output it says space "%d " this will be sufficient

1 Like

If all you wanna do is rotating array clockwise or anticlockwise, then there is a nice trick called “Rotation Trick”.

What you need to do, is to double and duplicate the array.

Eg, if array is arr= {1,2,3,4} then make it NewArr {1,2,3,4,1,2,3,4}.

On 1 right rotation, we will have {4,1,2,3} See, isnt it the subarray of NewArr from [4,7] (1-based indexing). For left rotation, you just have to change the direction of looking.
Another right rotation ={3,4,1,2}. Sub array of NewArr from [3,6]. I think you get the pattern.

Eg, after left rotation, array becomes {2,3,4,1}. Sub array from [2,5]. Another left, {3,4,1,2}. Sub array from [3,6].

Also, make sure that number of times to rotate is as -

Number of rotation = Number of Rotatio%n .Since after n rotation, we get original array back and we can save time by performing only needed/useful rotation.

1 Like

50 seconds difference. XD

haha brother you wrote it long thats y :slight_smile:

1 Like