Wednesday, February 21, 2018

[Interview Question] Program in java for Array Rotation

Objective : We will be given one array and asked to rotate the array by d no. of time 

ex- Input - {1,2,3,4,5} d=2
Output - {3,4,5,1,2} 
I will Recommend you to please do it by yourself before see the answer.

Approach 1 : Using temp Array

Pseudo code 
  1. We will use one temp array where we will add the element of value d
  2. then we will copy the d+1th element to 0th place d+2th element to 1th element and so on .
  3. Now we will merge the temp array elements at the end of the array.





Approach 2: Rotate by one to left 

Pseudo Code .


  1. We will first store the first element to temp variable.
  2. Move all the element to left by one.
  3. store the temp variable in last place.
Program Code:

Approach 3 : Reversal Algorithm

Pseudo Code

  1. Let suppose we need to rotate the array by d index what we will do is as below
  2. we first reverse the (o,d) element of the array 
  3. in second we will reverse the (d+1 , length) elements of the array .
  4. In third we will reverse (0, length ) element of the array this will give use the required array.

Program Code:


I guess the Code is self explanatory and I you still face any problem and looking for help , Please let me know , will be happy to help

If you like this article please share it with your friends and colleagues

Thanks for reading 
Noeik  

0 comments:

Post a Comment