Complete the code to rotate the array to the left by one position.
void rotateLeftByOne(int arr[], int n) {
int temp = arr[0];
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i [1] 1];
}
arr[n - 1] = temp;
}To shift elements left, we assign arr[i] = arr[i + 1]. So the operator is '+'.
Complete the code to rotate the array to the right by one position.
void rotateRightByOne(int arr[], int n) {
int temp = arr[n - 1];
for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i [1] 1];
}
arr[0] = temp;
}To shift elements right, we assign arr[i] = arr[i - 1]. So the operator is '-'.
Fix the error in the code to rotate the array left by d positions using reversal algorithm.
void reverse(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start [1] 1;
end [2] 1;
}
}
void rotateLeft(int arr[], int n, int d) {
d = d % n;
reverse(arr, 0, d - 1);
reverse(arr, d, n - 1);
reverse(arr, 0, n - 1);
}In the reverse function, use + to increment start and - to decrement end.
Fill both blanks to complete the code that rotates the array left by d positions using the juggling algorithm.
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a [1] b);
}
void rotateLeftJuggling(int arr[], int n, int d) {
d = d % n;
int g_c_d = gcd(n, d);
for (int i = 0; i < g_c_d; i++) {
int temp = arr[i];
int j = i;
while (true) {
int k = j [2] d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
arr[j] = temp;
}
}The gcd function uses modulo operator '%'. In the juggling algorithm, we move index by adding d, so '+' is used.
Fill all three blanks to complete the code that creates a dictionary mapping each element to its rotated position after left rotation by d.
std::unordered_map<int, int> rotatedPositions(const std::vector<int>& arr, int d) {
int n = arr.size();
std::unordered_map<int, int> posMap;
for (int i = 0; i < n; i++) {
int newPos = (i [1] d) [2] n;
if (newPos < 0) {
newPos[3]=n;
}
posMap[arr[i]] = newPos;
}
return posMap;
}To find new position after left rotation by d, we subtract d from i, then take modulo n. If result is negative, add n to wrap around.
