Challenge - 5 Problems
Array Insertion Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput after inserting elements at the beginning of an array
What is the output of the following Go code that inserts elements at the beginning of a slice?
DSA Go
package main import "fmt" func main() { arr := []int{3, 4, 5} arr = append([]int{2}, arr...) arr = append([]int{1}, arr...) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Remember that appending a slice with ... spreads the elements.
✗ Incorrect
The code inserts 2 at the beginning of the slice, then inserts 1 at the beginning again, resulting in [1 2 3 4 5].
❓ Predict Output
intermediateResulting slice after multiple insertions at the beginning
What will be printed after running this Go code that inserts multiple elements at the beginning of a slice?
DSA Go
package main import "fmt" func main() { s := []int{10, 20} s = append([]int{5}, s...) s = append([]int{1, 2, 3}, s...) fmt.Println(s) }
Attempts:
2 left
💡 Hint
Appending slices with ... adds all elements in order.
✗ Incorrect
First 5 is inserted at the beginning, then 1,2,3 are inserted before that, resulting in [1 2 3 5 10 20].
🔧 Debug
advancedIdentify the error in slice insertion at beginning
What error will this Go code produce when trying to insert an element at the beginning of a slice?
DSA Go
package main import "fmt" func main() { arr := []int{1, 2, 3} arr = append(arr, 0) copy(arr[1:], arr) arr[0] = 9 fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Check how copy is used and the slice lengths involved.
✗ Incorrect
The copy call tries to copy arr onto arr[1:], but arr[1:] is shorter than arr, causing out of range runtime error.
🧠 Conceptual
advancedTime complexity of inserting at the beginning of an array
What is the time complexity of inserting an element at the beginning of a dynamic array (slice) in Go?
Attempts:
2 left
💡 Hint
Think about what happens to existing elements when inserting at the start.
✗ Incorrect
Inserting at the beginning requires shifting all existing elements one position right, which takes O(n) time.
🚀 Application
expertEfficiently insert multiple elements at the beginning of a slice
Given a slice s := []int{4,5,6} and another slice prefix := []int{1,2,3}, which code snippet correctly and efficiently inserts all elements of prefix at the beginning of s?
Attempts:
2 left
💡 Hint
Appending prefix slice before s with ... spreads all elements.
✗ Incorrect
Appending prefix before s with s = append(prefix, s...) creates a new slice with prefix elements first, then s elements.
