Challenge - 5 Problems
Array Insertion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after inserting elements at the end of the array?
Consider the following Go code that inserts elements at the end of an array (slice). What will be printed?
DSA Go
package main import "fmt" func main() { arr := []int{1, 2, 3} arr = append(arr, 4) arr = append(arr, 5) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Remember that append adds elements to the end of the slice and returns the new slice.
✗ Incorrect
The append function adds elements to the end of the slice. Starting with [1 2 3], appending 4 and then 5 results in [1 2 3 4 5].
❓ Predict Output
intermediateWhat is the length of the array after insertions?
Given the following Go code, what is the length of the slice after all insertions?
DSA Go
package main import "fmt" func main() { arr := []int{10, 20} arr = append(arr, 30) arr = append(arr, 40, 50) fmt.Println(len(arr)) }
Attempts:
2 left
💡 Hint
Count the initial elements and all appended elements.
✗ Incorrect
Initial slice has 2 elements. Appending 30 adds 1 element, then appending 40 and 50 adds 2 more. Total length is 2 + 1 + 2 = 5.
❓ Predict Output
advancedWhat is the output of this slice insertion and print?
Analyze the Go code below. What will be printed?
DSA Go
package main import "fmt" func main() { arr := make([]int, 3) arr[0] = 7 arr[1] = 8 arr[2] = 9 arr = append(arr, 10) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Remember make creates a slice with zero values initially.
✗ Incorrect
make([]int, 3) creates a slice of length 3 with zeros. We assign values 7,8,9 to indices 0,1,2. Then append 10 adds it at the end. So output is [7 8 9 10].
❓ Predict Output
advancedWhat error occurs when appending to a nil slice?
What will happen when running this Go code?
DSA Go
package main import "fmt" func main() { var arr []int arr = append(arr, 1) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Appending to a nil slice is allowed in Go.
✗ Incorrect
In Go, appending to a nil slice creates a new slice with the appended element. So the output is [1].
🧠 Conceptual
expertWhat is the capacity of the slice after multiple append operations?
Given this Go code, what is the capacity of the slice after all append operations?
DSA Go
package main import "fmt" func main() { arr := make([]int, 0, 2) arr = append(arr, 1) arr = append(arr, 2) arr = append(arr, 3) fmt.Println(cap(arr)) }
Attempts:
2 left
💡 Hint
When capacity is exceeded, Go doubles the capacity.
✗ Incorrect
Initial capacity is 2. After appending 3 elements, capacity grows to 4 (doubled from 2).
