Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to rotate the array to the left by one position.
DSA Go
func rotateLeftByOne(arr []int) []int {
first := arr[0]
for i := 0; i < len(arr)-1; i++ {
arr[i] = arr[[1]]
}
arr[len(arr)-1] = first
return arr
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i-1 instead of i+1 causes index out of range error.
Assigning arr[i] = arr[0] copies the first element repeatedly.
✗ Incorrect
We move each element to the position of the previous element, so arr[i] = arr[i+1].
2fill in blank
mediumComplete the code to rotate the array to the right by one position.
DSA Go
func rotateRightByOne(arr []int) []int {
last := arr[len(arr)-1]
for i := len(arr)-1; i > 0; i-- {
arr[i] = arr[[1]]
}
arr[0] = last
return arr
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i+1 causes index out of range error.
Not updating arr[0] with the last element.
✗ Incorrect
We move each element to the position of the next element, so arr[i] = arr[i-1].
3fill in blank
hardFix the error in the code to rotate the array left by d positions using the reversal algorithm.
DSA Go
func reverse(arr []int, start int, end int) {
for start < end {
arr[start], arr[end] = arr[end], arr[start]
start++
end--
}
}
func rotateLeft(arr []int, d int) []int {
n := len(arr)
d = d % n
reverse(arr, 0, d-1)
reverse(arr, d, n-1)
reverse(arr, 0, [1])
return arr
}Attempts:
3 left
💡 Hint
Common Mistakes
Using d-1 or d as the end index causes incorrect rotation.
Not taking modulo of d with n causes index errors.
✗ Incorrect
After reversing the first d elements and the rest, we reverse the whole array from 0 to n-1 to complete the rotation.
4fill in blank
hardFill both blanks to complete the code that rotates the array right by d positions using the reversal algorithm.
DSA Go
func rotateRight(arr []int, d int) []int {
n := len(arr)
d = d % n
reverse(arr, 0, [1])
reverse(arr, n-d, n-1)
reverse(arr, 0, n-1)
return arr
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the indices for the two reverse calls.
Not taking modulo of d with n.
✗ Incorrect
To rotate right by d, first reverse the first n-d elements (0 to n-d-1), then last d elements, then the whole array.
5fill in blank
hardFill all three blanks to complete the code that rotates the array left by d positions using a temporary slice.
DSA Go
func rotateLeftTemp(arr []int, d int) []int {
n := len(arr)
d = d % n
temp := make([]int, d)
copy(temp, arr[[1]:[2]])
for i := 0; i < n-d; i++ {
arr[i] = arr[i+[3]]
}
for i := 0; i < d; i++ {
arr[n-d+i] = temp[i]
}
return arr
}Attempts:
3 left
💡 Hint
Common Mistakes
Copying wrong slice range to temp.
Incorrectly shifting elements causing overwrite.
✗ Incorrect
We copy the first d elements (0 to d) to temp, shift the rest left by d, then copy temp to the end.
