Stack Using Array - Problem
Implement a stack data structure using an array with the following operations:
- push(x) - Add element x to the top of the stack
- pop() - Remove and return the top element from the stack
- peek() - Return the top element without removing it
- isEmpty() - Check if the stack is empty
- size() - Return the number of elements in the stack
The stack should handle multiple operations efficiently and maintain Last In, First Out (LIFO) order.
You will be given a list of operations to perform on the stack. Each operation is represented as a list where the first element is the operation name and the second element (if present) is the value to push.
Input & Output
Example 1 — Basic Stack Operations
$
Input:
operations = [["push", 1], ["push", 2], ["peek"], ["pop"], ["isEmpty"]]
›
Output:
[2, 2, false]
💡 Note:
Push 1, push 2 (stack: [1,2]), peek returns 2, pop returns 2 (stack: [1]), isEmpty returns false
Example 2 — Empty Stack Operations
$
Input:
operations = [["push", 5], ["pop"], ["pop"], ["isEmpty"]]
›
Output:
[5, true]
💡 Note:
Push 5, pop returns 5 (stack empty), second pop on empty stack, isEmpty returns true
Example 3 — Size Tracking
$
Input:
operations = [["push", 10], ["push", 20], ["size"], ["pop"], ["size"]]
›
Output:
[2, 20, 1]
💡 Note:
Push 10, push 20, size is 2, pop 20, size is 1
Constraints
- 1 ≤ operations.length ≤ 1000
- -104 ≤ values ≤ 104
- Pop and peek operations on empty stack return null
- All operations should be handled efficiently
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code