
Problem
Solution
Submissions
Stack Using a List
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 10
Create a Python class called Stack
that implements a stack data structure using a list. The class should support standard stack operations such as push, pop, peek, is_empty, and size. The stack should follow the Last-In-First-Out (LIFO) principle.
Example 1
- Input: stack = Stack()
- Output: 30, 20
- Explanation:
- Step 1: Push elements like 10, 20, and 30 onto the stack.
- Step 2: Pop the top element (30) and then peek the next top (20).
Example 2
- Input: stack = Stack()
- Output: False, 2
- Explanation:
- Step 1: Check if the stack is empty (False if it contains elements).
- Step 2: Return the size of the stack (2 after two pushes).
Constraints
- The stack can contain elements of any data type
- Time Complexity: O(1) for all operations
- Space Complexity: O(n) where n is the number of elements in the stack
- Pop and peek operations on an empty stack should be handled gracefully
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use Python's built-in list to store the stack elements
- Define methods for each standard stack operation
- For push, use
list.append()
- For pop, use
list.pop()
with no arguments - Implement error handling for operations on an empty stack
- Consider implementing a max_size parameter (optional)