← Microsoft questions
CodingReported in a candidate post, Nov 2024

Implement stack data structure using an array

Filed under Microsoft

Free read 3 of 3

Confirm if the stack should have a fixed capacity or be dynamic.

The question

Implement a stack data structure using a dynamic array (or list) that supports push, pop, and peek operations.

Constraints

  • Operations must be O(1) average time complexity.
  • Handle empty stack underflow errors.
  • Dynamic resizing should be handled if using a fixed-size array.

Examples

Input
push(1), push(2), pop(), peek()
Output
1
Why
Pushing 1 then 2, popping 2 leaves 1 at the top.

Approach

  1. Confirm if the stack should have a fixed capacity or be dynamic.

Solution

O(1) time, O(N) space

Python
class Stack:
    def __init__(self): self.s = []
    def push(self, x): self.s.append(x)
    def pop(self): return self.s.pop() if self.s else None
    def peek(self): return self.s[-1] if self.s else None

Tips

  • What they are testing: Verify behavior when popping from an empty stack.
  • Common mistake: Forgetting to handle the case where the stack is empty during peek or pop operations.

Related Microsoft questions

Collected from public candidate posts and coding forums. Updated Nov 2026.