Challenge - 5 Problems
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of peeking the top element after these stack operations?
Consider a stack where we push 10, then 20, then 30. We then peek the top element without removing it. What is printed?
DSA Go
package main import "fmt" func main() { stack := []int{} stack = append(stack, 10) stack = append(stack, 20) stack = append(stack, 30) top := stack[len(stack)-1] fmt.Println(top) }
Attempts:
2 left
💡 Hint
Remember, peek returns the last pushed element without removing it.
✗ Incorrect
The last element pushed is 30, so peeking returns 30.
❓ Predict Output
intermediateWhat happens if you peek an empty stack?
Given an empty stack represented as a slice in Go, what happens if you try to peek the top element using stack[len(stack)-1]?
DSA Go
package main import "fmt" func main() { stack := []int{} top := stack[len(stack)-1] fmt.Println(top) }
Attempts:
2 left
💡 Hint
Think about accessing an element in an empty slice.
✗ Incorrect
Accessing stack[len(stack)-1] when stack is empty causes an index out of range panic.
🧠 Conceptual
advancedWhich statement about peeking the top element of a stack is true?
Select the correct statement about the peek operation on a stack.
Attempts:
2 left
💡 Hint
Peek should not change the stack size.
✗ Incorrect
Peek only returns the top element without removing it, so the stack remains unchanged.
🔧 Debug
advancedWhy does this peek implementation cause a runtime error?
Identify the cause of the runtime error in the following Go code that tries to peek the top element of a stack.
DSA Go
package main import "fmt" func peek(stack []int) int { return stack[0] } func main() { stack := []int{5, 10, 15} fmt.Println(peek(stack)) }
Attempts:
2 left
💡 Hint
Remember the top element is the last pushed element, not the first.
✗ Incorrect
The code returns stack[0], which is the bottom element, not the top. It does not cause runtime error but returns wrong element.
🚀 Application
expertHow many elements remain after peeking and popping twice from this stack?
Given a stack with elements [1, 2, 3, 4, 5] (1 is bottom, 5 is top), we peek once, then pop twice. How many elements remain in the stack?
Attempts:
2 left
💡 Hint
Peek does not remove elements, pop removes one element each time.
✗ Incorrect
Peek returns top element without removing it. Two pops remove two elements. Starting with 5 elements, after two pops 3 remain.
