[C++] Brute Force ▶️ O(n) & O(1) Solutions | Optimized | W/ Explanation
APPROACH 1 : Brute Force\n\n If k>=n do k = k%n\n Create a temp array of size k.\n Store the last k elements in a temp array.\n Shift the rest of the elements e
**APPROACH 1 : Brute Force**\n\n* If ```k>=n``` do ```k = k%n```\n* Create a ```temp``` array of size ```k```.\n* Store the last ```k``` elements in a temp array.\n* Shift the rest of the elements each by 1 position to the right.\n* Store the last ```k``` elements in the first ```k``` indices.\n\n**Time Complexity :** O(n)\n\n**Space Complexity :** O(k)\n\n**APPROACH 2 : Rotate k times**\n\n* Rotate all the elements by 1 position ```k``` times.\n\n**Time Complexity :** O()\n\n**Space Complexity :** O(1)\n\n**Code :**\n```\nclass Solution {\npublic:\n\tvoid rotateByOne(vector<int> &nums){\n\t\tint n = nums.size(), temp = nums[n-1];\n\t\tfor(int i=n-1; i>0; i--){\n\t\t\tnums[i] = nums[i-1];\n\t\t\tnums[0] = temp;\n\t\t}\n\t}\n    void rotate(vector<int>& nums, int k) {\n        for(int i=0; i<k; i++) rotateByOne(nums);\n    }\n};\n```\n\n**APPROACH 3 : Reversal of array**\n\n* Reverse the whole array.\n* Then reverse the first k elements.\n* Finally reverse the remaining elements.\n(Do a dry run, it\'s very easy to understand)\n\n**Time Complexity :** O(n)\n\n**Space Complexity :** O(1)\n\n**Code :**\n```\nclass Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n        k = k%nums.size();\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**Do upvote if you like my solutions & explanation :)**\n
['C', 'C++']