Complete the code to rotate the array to the right by one position.
int[] RotateRightByOne(int[] arr) {
int last = arr[arr.Length [1] 1];
for (int i = arr.Length - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = last;
return arr;
}We subtract 1 from the length to get the last index of the array.
Complete the code to rotate the array to the left by one position.
int[] RotateLeftByOne(int[] arr) {
int first = arr[[1]];
for (int i = 0; i < arr.Length - 1; i++) {
arr[i] = arr[i + 1];
}
arr[arr.Length - 1] = first;
return arr;
}The first element is at index 0, so we store arr[0] before shifting.
Fix the error in the code to rotate the array to the right by k positions.
int[] RotateRightByK(int[] arr, int k) {
int n = arr.Length;
k = k [1] n;
int[] rotated = new int[n];
for (int i = 0; i < n; i++) {
rotated[(i + k) % n] = arr[i];
}
return rotated;
}We use modulo to handle cases where k is larger than the array length.
Fill both blanks to create a dictionary that maps each element to its rotated position after left rotation by 1.
var rotationMap = new Dictionary<int, int>(); for (int i = 0; i < arr.Length; i++) { rotationMap[arr[i]] = (i [1] 1) [2] arr.Length; }
We subtract 1 to rotate left by one, then use modulo to wrap around the array length.
Fill all three blanks to create a dictionary comprehension that maps each element to its rotated position after right rotation by k.
var rotationMap = new Dictionary<int, int>(); for (int i = 0; i < arr.Length; i++) { int n = arr.Length; int pos = (i [1] k) [2] n; if (pos < 0) pos += n; rotationMap[arr[i]] = pos; }
We add k to i for right rotation, use modulo to wrap, and subtract k from i for negative check.
