Array - Left Rotation

 Content of the page: 

  • Question
  • Approach
  • Complete Code Solution


Que -  Left Rotation





ad


Approach - 
            
            For rotation of  Array index by D, we can use the formula --

                ( i + D ) % n

            
            i.e.  for array of  size 5  rotating with D = 2.
    
                    Traverse in the Array  -

                    ( 0 + 2 ) % 5  =  2 
                    ( 1 + 2 ) % 5  =  3
                    ( 2 + 2 ) % 5  =  4 
                    ( 3 + 2 ) % 5  =  0 
                    ( 4 + 2 ) % 5  =  1 

            now, we can create a new array, temp and push the elements one by one with the help of above                 formula 

            for  Left Rotation  --         temp[i] = Arr[( i + D ) % n]; 
                                       
                            for i =0,              temp [0] =  Arr[2]
                            for i =1,              temp [1] =  Arr[3]
                            for i =2,              temp [2] =  Arr[4]
                            for i =3,              temp [3] =  Arr[0]
                            for i =4,              temp [4] =  Arr[1]


            lly , for  Right Rotation  --      temp[( i + D ) % n] = Arr[i];           


ad



Round 1 : 




Round 2 : 


ad


Round 3 :




Round 4 :
   




Final Array :







ad



Complete Code : 



    vector<int> rotateLeft(int d, vector<int> arr) {

    vector<int> temp(arr.size());
    for(int i=0; i<arr.size(); i++){     temp[i] = arr[(i + d) % arr.size()];     }
    return temp;     }




ad

Post a Comment

0 Comments