Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

189. Rotate Array 🌟

Given an array, rotate the array to the right by k steps, where k is non-negative.

O(N) Time and O(N) space

Code

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> temp(nums.begin(),nums.end());

        // Rotate the elements.
        for(int i=0;i<n;i++){
            nums[(i+k)%n]=temp[i];
        }
    }
};

O(N) Time and O(1) Space

Code

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        k%=nums.size();
        reverse(nums.begin(),nums.end());
        reverse(nums.begin(),nums.begin()+k);
        reverse(nums.begin()+k,nums.end());
    }
};