Created
January 11, 2022 17:46
-
-
Save Kanav-Arora/97887429c27ddca3bc00c02e88bb1a1b to your computer and use it in GitHub Desktop.
Rotate Array K Times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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