krahets/hello-algo · error · IndexError
Stack is empty
Error message
Stack is empty
What it means
Raised by LinkedListStack#peek (en/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb:41) when the stack is empty. peek returns @peek.val; @peek is nil at size == 0, so the guard prevents a nil dereference. pop calls peek first, so popping an empty linked-list stack also surfaces this message.
Source
Thrown at en/codes/ruby/chapter_stack_and_queue/linkedlist_stack.rb:41
### Push ###
def push(val)
node = ListNode.new(val)
node.next = @peek
@peek = node
@size += 1
end
### Pop ###
def pop
num = peek
@peek = @peek.next
@size -= 1
num
end
### Access top element ###
def peek
raise IndexError, 'Stack is empty' if is_empty?
@peek.val
end
### Convert linked list to Array and return ###
def to_array
arr = []
node = @peek
while node
arr << node.val
node = node.next
end
arr.reverse
end
end
### Driver Code ###
if __FILE__ == $0View on GitHub (pinned to 69932aed18)
Solutions
- Guard with stack.is_empty? before peek/pop.
- Keep push and pop counts balanced; assert before unwinding.
- Rescue IndexError and return a sentinel for the empty-top case.
Example fix
# before top = stack.peek # raises on empty # after top = stack.is_empty? ? nil : stack.peek
Defensive patterns
Strategy: validation
Validate before calling
stack.peek unless stack.is_empty?
Type guard
def stack_nonempty?(s); s.respond_to?(:is_empty?) && !s.is_empty?; end
Try / catch
begin stack.peek rescue IndexError nil end
Prevention
- Guard peek/pop with is_empty?.
- Maintain balanced push/pop in recursion/backtracking.
- Push a sentinel for algorithms that peek unconditionally.
When it happens
Trigger: Calling stack.peek or stack.pop when stack.size == 0 — before any push, or after the list has been fully unwound by pops.
Common situations: A recursive/backtracking stack drained by unwind; a delimiter/matching stack where the input closes more groups than it opened; peeking the top before the first push.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/543c554077f939b4.
Report an issue: GitHub.