Design Stack (Array-backed)
Easy
JavaDesignStack
Problem
Design a class MyStack using an array. Implement push(int), pop() (returns the popped value), top(), and empty().
Example 1
Input: push(1); push(2); top()
Output: 2
Constraints
- 1 ≤ ops ≤ 1000
Approach — Stack
This is a Stack problem. The idea: scan the input once, pushing work onto a stack and popping when the top can be resolved, so the stack always reflects what's still open. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class MyStack:
def __init__(self):
self.data = []
def push(self, x):
self.data.append(x)
def pop(self):
return self.data.pop()
def top(self):
return self.data[-1]
def empty(self):
return len(self.data) == 0
Java
class MyStack {
private int[] buf = new int[10000];
private int n = 0;
public void push(int x) { buf[n++] = x; }
public int pop() { return buf[--n]; }
public int top() { return buf[n - 1]; }
public boolean empty() { return n == 0; }
}
class Solution {}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Design Stack (Array-backed) interactively → ← All solutions