Skip to content

Commit

Permalink
Status:solved
Browse files Browse the repository at this point in the history
  • Loading branch information
Sundar2k4 committed Aug 6, 2024
1 parent 5c35f81 commit 99727d3
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions Righrotatearr.c++
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <iostream>
#include <vector>
using namespace std;

class Solution
{
public:
void rotate(vector<int> &nums, int k)
{
int n = nums.size();
k = k % n; // Handle cases where k >= n

if (k == 0)
return; // No rotation needed if k is 0 or a multiple of n

// Create a temporary vector to store the last k elements
vector<int> temp(k);

// Store the last k elements in the temp vector
for (int i = 0; i < k; i++)
{
temp[i] = nums[n - k + i];
}

// Shift the remaining elements to the right by k positions
for (int i = n - k - 1; i >= 0; i--)
{
nums[i + k] = nums[i];
}

// Move the elements from temp to the front of the array
for (int i = 0; i < k; i++)
{
nums[i] = temp[i];
}
}
};

int main()
{
Solution solution;
vector<int> nums = {4, 5, 6, 7, 1, 2, 3}; // Example array
int k = 3; // Number of positions to rotate

cout << "Original array: ";
for (int num : nums)
{
cout << num << " ";
}
cout << endl;

solution.rotate(nums, k);

cout << "Rotated array: ";
for (int num : nums)
{
cout << num << " ";
}
cout << endl;

return 0;
}

0 comments on commit 99727d3

Please sign in to comment.