Leetcode 189 Solution

This article provides solution to leetcode question 189 (rotate-array)

https://leetcode.com/problems/rotate-array

Solution

class Solution {
public:
    int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }

    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        int m = gcd(n, k);

        for (int i = 0; i < m; i++)
        {
            int j = i;

            int curr = nums[j];

            do
            {
                int tmp = nums[(j + k) % n];
                nums[(j + k) % n] = curr;

                j = (j + k) % n;
                curr = tmp;
            } while (j != i);
        }
    }
};