C++ | 3 methods | Fast | Explained
This took a lot of effort to document. Please upvote if helpful\n\nMethod-1\nMost elementary method is by creating a  copy of given array and exploiting defn of
**This took a lot of effort to document. Please upvote if helpful**\n\n**Method-1**\nMost elementary method is by creating a  copy of given array and exploiting defn of rotation: *nums[(i+k)%n] = old_nums[i]*.\nTC: O(n)\nSC: O(n)\n```\nclass Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n        int n=nums.size();\n        vector<int> cpy(nums.cbegin(), nums.cend());\n        \n        for (int i = 0; i < n; i++) {\n            nums[(i+k)%n] = cpy[i];\n        }\n    }\n};\n```\n\n**Method-2**\nHere, we reduce the space complexity from O(n) to O(1). Note that the rotated array consists of two parts of the main array- one from [k..n-1], and otehr from [0..k-1]. Note that the part from [0..k-1] follows [k..n-1]. So, we reverse the main array, and re-reverse it in two parts- [0..k-1] and [k..n-1].\nTC: O(n)\nSC: O(1)\n```\nclass Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n        int n = nums.size();\n        k %= n;\n        \n        reverse(nums.begin(), nums.end());\n        reverse(nums.begin(), nums.begin()+k);\n        reverse(nums.begin()+k, nums.end());\n        \n        return;\n    }\n};\n```\n\n**Method-3**\nThis is fairly mathematically involved, and some interest in number theory is expected. Although it too used O(n) space, but instead of storing *n integers*, we store *n booleans*; also this is mainly for mathematic interests. For *n*, and *k*, we have two cases-\nCase i: *gcd(n,k) = 1*\nS = {(i+k)%n | i=0 or i \\in S} = {i | 0<=i and i<n}\nCase ii: *gcd(n,k) = d != 1*\nSt = {(i+k)%n | i=t or i \\in S}; union of whom for t=0 to t=d-1, will equal {i | 0<=i and i<n}.\nTC: O(n)\nSC: O(n)\n```\nclass Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n        int n = nums.size();\n        k %= n;\n        vector<bool> visited(n, false);\n\n        int curr_idx = 0, curr_val = nums[0], next_idx = k;\n        for (int i = 0; i < n;i++) {\n            if (!visited[i]) {\n                curr_idx = i;\n                next_idx = (i + k) % n;\n                curr_val = nums[i];\n                while (!visited[next_idx]) {\n                    visited[next_idx] = true;\n                    swap(curr_val, nums[next_idx]);\n                    curr_idx = next_idx;\n                    next_idx = (curr_idx + k) % n;\n                }\n            }\n        }\n    }\n};\n```\n\n**Please upvote, if helpful; as this took a lot of effort**
['Array', 'C', 'C++']