Skip to content

Instantly share code, notes, and snippets.

@ag8023
Created February 7, 2025 01:20
Show Gist options
  • Save ag8023/ae52d639b2f2dda2c199b92cb043e651 to your computer and use it in GitHub Desktop.
Save ag8023/ae52d639b2f2dda2c199b92cb043e651 to your computer and use it in GitHub Desktop.
class Solution {
public:
void reverse(vector<int> &nums, int start, int end){
while(start < end){
swap(nums[start], nums[end]);
start++;
end--;
}
}
void rotate(vector<int>& nums, int k) {
k = k%nums.size(); // to get the actual rotation pattern
//brute force
int n = nums.size();
// vector<int> temp(k);
// // first move the last k elements to temp (since we are doing a right shift)
// for(int i = 0; i < k; i++){
// temp[i] = nums[(n-k)+ i];
// cout << temp[i] << endl;
// }
// for(const auto &elem : nums){
// cout << elem << " " << endl;
// }
// // now shift the first n-k elements of the input vector to the back of the array
// for(int i = 0 ; i < n-k; i++){
// cout << n-k-1 << " + " << i << " = " << nums[n-k-1 + i] << endl;
// cout << nums[i] << endl;
// nums[n-k-1 + i] = nums[i];
// }
// // now copy back the contents of temp at the front of the arrya(since we are doing a right shift)
// for(int i = 0; i < k; i++){
// nums[i] = temp[i];
// }
//optimal solution
reverse(nums, 0, n-1);
for(const auto &elem : nums){
cout << elem << " " << endl;
}
reverse(nums, 0, k-1);
reverse(nums, k, n-1);
}
};
@ag8023
Copy link
Author

ag8023 commented Feb 7, 2025

I am unable to get my brute force solution to work, need help with that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment