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) {
if s.size == len(s.data) {
s.resize(s.size * 2)
}
s.data[s.size] = [1]
s.size++
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' instead of 'value' to assign the element.
Using 'data' which is the slice, not the element.
✗ Incorrect
We push the given value onto the stack at the current size index.
2fill in blank
mediumComplete the code to pop an element from the stack.
DSA Go
func (s *Stack) Pop() (int, bool) {
if s.size == 0 {
return 0, false
}
s.size--
value := s.data[[1]]
s.data[s.size] = 0
if s.size > 0 && s.size == len(s.data)/4 {
s.resize(len(s.data) / 2)
}
return value, true
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 's.size - 1' after decrement, causing off-by-one error.
Using 0 or len(s.data) which are incorrect indices.
✗ Incorrect
We access the element at index s.size because size was decremented before.
3fill in blank
hardFix the error in the resize method to correctly copy elements to the new array.
DSA Go
func (s *Stack) resize(capacity int) {
newData := make([]int, capacity)
for i := 0; i < s.size; i++ {
newData[i] = [1]
}
s.data = newData
}Attempts:
3 left
💡 Hint
Common Mistakes
Copying from newData instead of s.data causes zero values.
Using capacity or s.size as values instead of elements.
✗ Incorrect
We copy elements from the old data slice at index i to the new slice.
4fill in blank
hardFill both blanks to complete the Peek method that returns the top element without removing it.
DSA Go
func (s *Stack) Peek() (int, bool) {
if s.size == 0 {
return 0, false
}
return s.data[[1]], [2]
}Attempts:
3 left
💡 Hint
Common Mistakes
Using s.size as index causes out-of-range error.
Returning false incorrectly when stack has elements.
✗ Incorrect
Peek returns the element at index size-1 and true to indicate success.
5fill in blank
hardFill all three blanks to complete the IsEmpty method that checks if the stack is empty.
DSA Go
func (s *Stack) IsEmpty() bool {
return [1] == [2] || s.size == [3]
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing size to len(s.data) or capacity which is incorrect.
Using wrong variables for emptiness check.
✗ Incorrect
Stack is empty if size equals zero; len(s.data) or capacity are not used here.
