Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element onto the stack.
DSA Go
func (s *Stack) Push(value int) {
s.items = append(s.items, [1])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name instead of 'value'.
Trying to append the entire stack instead of the new value.
✗ Incorrect
The Push method adds the given value to the end of the items slice representing the stack.
2fill in blank
mediumComplete the code to initialize a new empty stack.
DSA Go
func NewStack() *Stack {
return &Stack{items: [1]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using nil which can cause runtime errors when appending.
Using make with incorrect length or missing capacity.
✗ Incorrect
An empty slice literal '[]int{}' initializes the items slice as empty for the new stack.
3fill in blank
hardFix the error in the Push method to correctly add the value to the stack.
DSA Go
func (s *Stack) Push(value int) {
s.items = append([1], value)
}Attempts:
3 left
💡 Hint
Common Mistakes
Appending to the wrong variable or value.
Using the stack pointer 's' directly instead of its items slice.
✗ Incorrect
The append function must add 'value' to the slice 's.items' to update the stack correctly.
4fill in blank
hardFill both blanks to complete the Pop method that removes and returns the top element of the stack.
DSA Go
func (s *Stack) Pop() (int, bool) {
if len(s.items) == 0 {
return 0, false
}
top := s.items[len(s.items) [1]]
s.items = s.items[:len(s.items) [2]]
return top, true
}Attempts:
3 left
💡 Hint
Common Mistakes
Using +1 which causes out-of-range errors.
Using -2 which removes two elements instead of one.
✗ Incorrect
To get the last element, subtract 1 from the length. To remove it, slice up to length minus 1.
5fill in blank
hardFill all three blanks to complete the Peek method that returns the top element without removing it.
DSA Go
func (s *Stack) Peek() (int, bool) {
if len(s.items) == 0 {
return 0, false
}
return s.items[len(s.items) [1]], [2]
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning false which indicates failure.
Using +1 which causes index out of range.
✗ Incorrect
Peek returns the last element at index length - 1 and true indicating success.
