Brute +Optimized | Logic Explained | Time complexity : O(n)
Intuition\nSuppose the question was to rotate right by one place,\neg: [1,2,3,4,5]  k=1\n    then we would have:\n   1. stored the last element in some temporar
# Intuition\nSuppose the question was to rotate right by one place,\neg: [1,2,3,4,5]  k=1\n    then we would have:\n   1. stored the last element in some temporary variable .\n   2. shifted all the elements to the right-->nums[i]=nums[i-1].\n   3. finally,put the temporary variable in the first index -->nums[0]=temp.\n\nwe will the same logic to solve this problem\n\n# Approach\n- observe carefully and try to compare the problem with the above one\n- store the last \'k\' elements in some temporary array\n- now start shifting the \'n-k\' elements to the end\n- finally place the temporary array to the beginning \'k\' positions.\n- it might be confusing at first but trying doing it in pen and paper \n\n           \n\n\n# Complexity\n- Time complexity:\n  This solution takes linear time complexity ->O(n)\n\n- Space complexity:\n  We are using an extra temp array , hence \n  space complexity ->O(n) , where n is the size of the array\n\n# Code\n```\nclass Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n         int n=nums.size();\n         k=k%n;\n\n        vector<int>temp(k);\n   \n        int i=0;\n        for(int j=n-k;j<n;j++){  \n            temp[i]=nums[j];  \n            i++;\n        }\n\n        i=n-1;  \n        for(int j=n-k-1;j>=0;j--){\n            nums[i]=nums[j];\n            i--; \n        }\n        \n       for(int j=0;j<=i;j++){    \n           nums[j]=temp[j];      \n                                  \n        }\n\n    }\n};\n\n<!-- DRY RUN\n\neg: [1,2,3,4,5,6,7]  ; k=3\nj=4 (n-k) \n\ntemp=[5,6,7]\n\ni=6;\n\n[1,2,3,4,5,6,7]  \n\nnums[6]=nums[3]---->[1,2,3,4,5,6,4]\nnums[5]=nums[2]---->[1,2,3,4,5,3,4]\nnums[4]=nums[1]---->[1,2,3,4,2,3,4]\nnums[3]=nums[0]---->[1,2,3,1,2,3,4]\n\n\ni=2;   \n\nnums[0]=temp[0]---->[5,2,3,1,2,3,4]  \nnums[1]=temp[1]---->[5,6,3,1,2,3,4] \nnums[2]=temp[2]---->[5,6,7,1,2,3,4] \n\n\n```\n\n# Without using extra space \n- It is purely based on observation and if asked in any interview first tell the above solution. \n- Reverse the complete array\n- Then , reverse the first k elements.\n- Finally , reverse the last n-k elements\n- eg:  [1,2,3,4,5,6,7] k=3\nI.   [7,6,5,4,3,2,1]\nII.  [5,6,7,4,3,2,1]\nIII. [5,6,7,1,2,3,4]\n\n# Code\n```\nclass Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n        int l=nums.size();\n        k%=l;\n        reverse(nums.begin(),nums.end());\n        reverse(nums.begin(),nums.begin()+k);\n        reverse(nums.begin()+k,nums.end());      \n    }\n};\n\n\n\n\n
['C++']