Skip to content

Instantly share code, notes, and snippets.

@Kanav-Arora
Created January 11, 2022 17:46
Show Gist options
  • Save Kanav-Arora/97887429c27ddca3bc00c02e88bb1a1b to your computer and use it in GitHub Desktop.
Save Kanav-Arora/97887429c27ddca3bc00c02e88bb1a1b to your computer and use it in GitHub Desktop.
Rotate Array K Times
/*
Space complexity - O(1) in-place
Time Complexity - O(N)
*/
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k - (k/nums.size())*nums.size();
reverse(nums, 0,nums.size()-k-1);
reverse(nums, nums.size()-k ,nums.size()-1);
reverse(nums,0,nums.size()-1);
}
void reverse(vector<int>& nums, int low, int high)
{
while(low<high)
{
swap(nums[low],nums[high]);
low++;
high--;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment