Array rotation - gives correct output but exceeds time limit : Please suggest some changes :)

  #include <iostream>

int main() 
{
  unsigned int t;
 std::cin >> t;
  while (t--)
{
 int n;
 std::cin >> n;
 
 int d ;
 std::cin >> d; 
 
 int arr[n] ;
  for (int i=0; i<n ;++i)
   {
     std::cin >> arr[i];
   }

   for (int i=0; i<d;++i)
    {
      int temp;
      temp = arr[0];
        for (int j=0 ;j <n ;++j)
          {
            arr[j] = arr[j+1];
          }
      arr[n-1] = temp;
    }
      for (int i=0 ;i< n ;++i)
         {
             std::cout << arr[i] << " ";
            }

            std::cout << '\n';
         }	

return 0;
}

Problem Link ??

2 Likes

https://practice.geeksforgeeks.org/problems/rotate-array-by-n-elements/0

So in the problem you need to do left shift of elements from starting upto d elements. What you are doing is a brute force approach. Simply print the elements after dth index and then print the element upto d index it will work. Like given below

 for(int i=d;i<n;i++) cout<<arr[i]<<" ";
        
        for(int i=0;i<d;i++) cout<<arr[i]<<" "; cout<<"\n";
1 Like

Thank you very much … Solution was very short than I expected !

1 Like