Challenge - 5 Problems
Slice and Array Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of modifying a slice element
What is the output of this Go program?
Go
package main import "fmt" func main() { arr := [3]int{1, 2, 3} s := arr[:] s[1] = 10 fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Slices share the underlying array with the original array.
✗ Incorrect
Changing an element of the slice changes the underlying array because the slice references the same memory.
❓ Predict Output
intermediate2:00remaining
Length and capacity of a slice
What will be printed by this Go code?
Go
package main import "fmt" func main() { arr := [5]int{1, 2, 3, 4, 5} s := arr[1:4] fmt.Println(len(s), cap(s)) }
Attempts:
2 left
💡 Hint
Length is the number of elements in the slice; capacity is from the start of the slice to the end of the array.
✗ Incorrect
The slice s covers elements at indices 1,2,3 (length 3). Capacity is from index 1 to end of arr (5 elements total), so capacity is 4.
🔧 Debug
advanced2:00remaining
Why does this slice append not change the original array?
Consider this Go code snippet. What is the output and why?
Go
package main import "fmt" func main() { arr := [3]int{1, 2, 3} s := arr[:2] s = append(s, 4) fmt.Println(arr) fmt.Println(s) }
Attempts:
2 left
💡 Hint
Appending to a slice may create a new underlying array if capacity is exceeded.
✗ Incorrect
The slice s has length 2 and capacity 3. Appending one element increases length to 3, which fits in capacity. Append modifies the underlying array by setting arr[2]=4. So arr becomes [1 2 4]. Both arr and s reflect [1 2 4].
📝 Syntax
advanced2:00remaining
Identify the syntax error in slice declaration
Which option contains a syntax error in slice or array usage?
Attempts:
2 left
💡 Hint
Go slice syntax uses a single colon, not two dots.
✗ Incorrect
The slice syntax uses a single colon between indices, e.g., arr[1:3]. Using two dots causes a syntax error.
🧠 Conceptual
expert2:00remaining
Effect of modifying a slice after re-slicing
Given the code below, what is the output?
Go
package main import "fmt" func main() { arr := [5]int{10, 20, 30, 40, 50} s1 := arr[1:4] s2 := s1[1:3] s2[0] = 100 fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Slices share the same underlying array. Indexes are relative to the original array.
✗ Incorrect
s1 is arr[1:4] → elements at indices 1,2,3. s2 is s1[1:3] → elements at indices 2,3 of arr. Modifying s2[0] changes arr[2].