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
INPUTALGORITHMRESULTOperations List["push", 1]["push", 2]["peek"]["pop"]Array-Based Stack1Initialize empty array2Push elements to array end3Peek returns top element4Pop removes from end12[0]topOutput Values[2, 2, false]peek() → 2pop() → 2isEmpty() → falseKey Insight:Using array end as stack top enables O(1) push/pop operations without shifting elementsTutorialsPoint - Stack Using Array | Optimal Array Implementation
Asked in
Microsoft 25 Amazon 20 Google 15
24.9K Views
High Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen