How Stacks Work — API Cheat Sheet
No exercise here — push/pop/peek across Java, C#, Python, and JavaScript/TypeScript, and which type to actually use in each language.
This is a reference page, not a graded exercise. A stack is last-in-first-out (LIFO): the last thing you pushed is the first thing you pop. Reach for it for matching/nesting problems (parentheses, undo history), and for turning recursion into an explicit loop.
Java — use Deque<T>, not the old Stack class
Java has a legacy Stack class, but its own documentation recommends against it (it's synchronized, which you don't need, and extends Vector). Use Deque instead:
| Want to... | Method | Example |
|---|---|---|
| Create | new ArrayDeque<>() | Deque<Integer> stack = new ArrayDeque<>(); |
| Push | .push(v) | stack.push(5); |
| Pop | .pop() | removes and returns the top; throws if empty |
| Peek | .peek() | returns the top without removing; returns null if empty |
| Check empty | .isEmpty() |
C# — Stack<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new Stack<T>() | var stack = new Stack<int>(); |
| Push | .Push(v) | |
| Pop | .Pop() | throws if empty |
| Peek | .Peek() | throws if empty — check .Count first |
| Size | .Count | property |
Python — just use a list
No dedicated stack class needed — a plain list's end is O(1) for both operations:
| Want to... | Method | Example |
|---|---|---|
| Push | .append(v) | |
| Pop | .pop() | pops from the end; throws IndexError if empty |
| Peek | lst[-1] | negative indexing reaches the last element |
JavaScript / TypeScript — just use an Array
| Want to... | Method | Example |
|---|---|---|
| Push | .push(v) | pushes to the end |
| Pop | .pop() | pops from the end; returns undefined if empty |
| Peek | arr[arr.length - 1] | no built-in .peek() |
The gotcha that costs the most time: in Python and JS, you push/pop from the end of the list/array, not the front — .pop() on an array is O(1) precisely because it operates on the end. If you instead call .pop(0) (Python) or .shift() (JS), you're doing a queue operation, not a stack operation, and it's O(n) too.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.