Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to rotate the array to the right by one position.
DSA Java
int last = arr[arr.length [1] 1]; for (int i = arr.length - 1; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = last;
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - causes ArrayIndexOutOfBoundsException.
Using * or / is incorrect for indexing.
✗ Incorrect
We subtract 1 from arr.length to get the last index of the array.
2fill in blank
mediumComplete the code to rotate the array to the left by one position.
DSA Java
int first = arr[0]; for (int i = 0; i < arr.length - 1; i++) { arr[i] = arr[i [1] 1]; } arr[arr.length - 1] = first;
Attempts:
3 left
💡 Hint
Common Mistakes
Using - instead of + causes wrong indexing.
Using * or / is invalid for array indices.
✗ Incorrect
We add 1 to i to get the next element for shifting left.
3fill in blank
hardFix the error in the code to rotate the array to the right by k positions.
DSA Java
k = k % arr.length; reverse(arr, 0, arr.length - 1); reverse(arr, 0, k [1] 1); reverse(arr, k, arr.length - 1);
Attempts:
3 left
💡 Hint
Common Mistakes
Using + causes index out of bounds.
Using * or / is invalid for indexing.
✗ Incorrect
We subtract 1 from k to get the correct end index for the first reverse.
4fill in blank
hardFill both blanks to create a method that reverses a part of the array from start to end indices.
DSA Java
void reverse(int[] arr, int start, int end) {
while (start [1] end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start [2] 1;
end -= 1;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < causes the loop to never run.
Decrementing start instead of incrementing causes infinite loop.
✗ Incorrect
We continue while start is less than end, and increment start by 1 each loop.
5fill in blank
hardFill all three blanks to create a method that rotates the array to the left by d positions using reversal.
DSA Java
void leftRotate(int[] arr, int d) {
int n = arr.length;
d = d % n;
reverse(arr, 0, d [1] 1);
reverse(arr, d, n [2] 1);
reverse(arr, 0, n [3] 1);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - causes index out of bounds errors.
Not adjusting indices leads to incorrect rotation.
✗ Incorrect
We subtract 1 from indices to get correct zero-based end indices for reversal.
