Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert an element at the beginning of the slice.
DSA Go
arr := []int{2, 3, 4}
newElement := 1
arr = append([]int{newElement}, arr[1])
fmt.Println(arr)Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use '...' causes a nested slice instead of a flat slice.
Appending without '...' results in a nested slice.
✗ Incorrect
The append function in Go can add elements to a slice. To insert at the beginning, we append the original slice after the new element slice using '...'.
2fill in blank
mediumComplete the code to shift elements right before inserting at the beginning.
DSA Go
arr := []int{2, 3, 4}
arr = append(arr, 0)
copy(arr[1:], arr[[1]:])
arr[0] = 1
fmt.Println(arr)Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong start index in copy causes data overwrite or missing elements.
Not appending extra space before copying causes out-of-range errors.
✗ Incorrect
To shift elements right, copy from index 0 to index 1 onwards. So, copy(arr[1:], arr[0:]) shifts all elements right by one.
3fill in blank
hardFix the error in the code to insert at the beginning without losing elements.
DSA Go
arr := []int{2, 3, 4}
arr = append(arr, 0)
copy(arr[1:], arr[[1]:])
arr[0] = 1
fmt.Println(arr)Attempts:
3 left
💡 Hint
Common Mistakes
Starting copy from index 1 causes the first element to be lost.
Not appending space before copy causes runtime panic.
✗ Incorrect
The copy must start from index 0 to shift all elements right. Using 1 or other indices skips elements or causes errors.
4fill in blank
hardFill both blanks to create a function that inserts an element at the beginning of a slice.
DSA Go
func insertAtBeginning(arr []int, val int) []int {
arr = append(arr, 0)
copy(arr[[1]:], arr[[2]:])
arr[0] = val
return arr
}
fmt.Println(insertAtBeginning([]int{2,3,4}, 1))Attempts:
3 left
💡 Hint
Common Mistakes
Swapping source and destination indices causes incorrect shifting.
Using wrong indices causes data loss or runtime errors.
✗ Incorrect
To shift elements right, copy from index 0 to index 1 onwards. So, copy(arr[1:], arr[0:]) shifts all elements right by one.
5fill in blank
hardFill all three blanks to create a function that inserts multiple elements at the beginning of a slice.
DSA Go
func insertMultipleAtBeginning(arr []int, vals []int) []int {
arr = append(arr, make([]int, len(vals))...)
copy(arr[[1]:], arr[[2]:])
copy(arr[0:], vals[[3]:])
return arr
}
fmt.Println(insertMultipleAtBeginning([]int{3,4,5}, []int{1,2}))Attempts:
3 left
💡 Hint
Common Mistakes
Not appending enough space for new elements causes overwrite.
Incorrect indices in copy cause data loss or panic.
✗ Incorrect
We append space for vals length, shift original elements right by len(vals), then copy vals starting from index 0.
