Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the top element of the stack without removing it.
DSA Go
func (s *Stack) Peek() int {
if len(s.items) == 0 {
return -1
}
return s.items[1]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using index 0 instead of the last index.
Using len(s.items) which is out of range.
✗ Incorrect
The top element of the stack is at the last index, which is len(s.items)-1.
2fill in blank
mediumComplete the code to check if the stack is empty before peeking.
DSA Go
func (s *Stack) Peek() (int, bool) {
if [1] {
return 0, false
}
return s.items[len(s.items)-1], true
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking if len(s.items) > 0 instead of == 0.
Checking if s.items == nil which may not be reliable.
✗ Incorrect
We check if the length of items is zero to know if the stack is empty.
3fill in blank
hardFix the error in the Peek method to avoid runtime panic when stack is empty.
DSA Go
func (s *Stack) Peek() int {
if len(s.items) == 0 {
return [1]
}
return s.items[len(s.items)-1]
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning s.items[0] causes panic if stack is empty.
Returning nil is invalid for int return type.
✗ Incorrect
Returning -1 indicates the stack is empty without causing panic.
4fill in blank
hardFill both blanks to implement Peek that returns value and success flag.
DSA Go
func (s *Stack) Peek() (int, bool) {
if [1] {
return 0, [2]
}
return s.items[len(s.items)-1], true
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning true when stack is empty.
Checking len(s.items) > 0 instead of == 0.
✗ Incorrect
Check if stack is empty and return false flag if yes.
5fill in blank
hardFill all three blanks to implement Peek with error handling using ok flag.
DSA Go
func (s *Stack) Peek() (int, bool) {
if [1] {
return [2], [3]
}
return s.items[len(s.items)-1], true
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning -1 instead of 0 for empty stack.
Returning true when stack is empty.
✗ Incorrect
Return 0 and false if stack is empty, else top element and true.
