-
Notifications
You must be signed in to change notification settings - Fork 0
Stack
krishanthan4 edited this page Dec 16, 2025
·
1 revision
Implement a stack data structure that follows the Last-In-First-Out (LIFO) principle.
A stack is a linear data structure where elements are added and removed from the same end (the "top"). Like a stack of plates, you can only add or remove from the top.
-
Time Complexity:
- Push: O(1)
- Pop: O(1)
- Peek: O(1)
- Space Complexity: O(n) where n is number of elements
- Access Pattern: LIFO (Last In, First Out)
- Implementation: Can use array or linked list
- Push: Add an element to the top
- Pop: Remove and return the top element
- Peek: View the top element without removing it
- isEmpty: Check if stack is empty
- size: Get the number of elements
Implement the following methods in Stack.java:
-
push(T element)- Add element to top -
pop()- Remove and return top element -
peek()- Return top element without removing -
isEmpty()- Check if empty -
size()- Return number of elements
- Pros: Fast access, cache-friendly
- Cons: Fixed size (needs resizing)
- When to resize: When array is full
- Pros: Dynamic size, no resizing needed
- Cons: Extra memory for pointers
- Push multiple elements and pop them
- Peek without removing
- Pop from empty stack (should throw exception)
- Check isEmpty on empty and non-empty stack
- Push beyond initial capacity (test resizing)
- Mixed operations
- For array implementation: keep a
topindex - When array is full, create new array with double capacity
- Throw
EmptyStackExceptionwhen popping/peeking empty stack - Consider using generics for type safety
- Function call stack (recursion)
- Undo/Redo functionality
- Expression evaluation (infix to postfix)
- Backtracking algorithms
- Browser history (back button)
- Syntax parsing
- Depth-First Search
- Balanced parentheses checker
- Evaluate postfix expressions
- Convert infix to postfix
- Next greater element
- Stock span problem
- Implement queue using stacks
- How would you implement a stack that supports getMin() in O(1)?
- How would you reverse a stack using recursion?
- How would you implement two stacks in one array?
- Can you implement a stack that automatically keeps track of its maximum element?
- Not handling empty stack errors
- Array index out of bounds when not resizing
- Memory leaks (not clearing references in array implementation)
- Not updating size counter
- Operations on empty stack
- Single element stack
- Stack at capacity (for array implementation)
- Null elements (should you allow them?)
- Queue (FIFO counterpart)
- Deque (double-ended queue)
- Priority Queue