Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Validate parenthesesE02. Reverse a string using a stackE03. Implement a stack with push, pop, and peekE

Problem No 3

Implement a stack with push, pop, and peek

Easy

10 minute session

Summary

Build a simple Stack class supporting push, pop, and peek operations.

Problem statement

Design and implement a Stack class with the following methods: push(value) -> returns None, pop() -> returns top value or None if the stack is empty, peek() -> returns top value or None if empty. Also implement a helper function process_operations(ops) that accepts a list of ('push', value) / ('pop', None) / ('peek', None) tuples and returns a list of results (one entry per operation). Use a list internally to represent the stack.

Task

Implement a Stack class where push adds an element, pop removes and returns the top element (or None if empty), and peek returns the top element without removing it (or None if empty). Provide a helper to simulate a sequence of operations.

Examples

Push, peek, pop

Input

process_operations([('push', 1), ('peek', None), ('pop', None)])

Output

[None, 1, 1]

Explanation

push returns None, peek shows 1, pop removes and returns 1.

Input format

A Python list of tuples ops where each tuple is ('push', value) or ('pop', None) or ('peek', None). Example: [('push', 5), ('peek', None)]

Output format

Return a list containing the return value of each operation in order. push returns None.

Constraints

Number of operations up to 10^4. All values are allowed Python objects (integers, strings, etc.).

Samples

Sample input 0

process_operations([('push', 10), ('push', 20), ('pop', None)])

Sample output 0

[None, None, 20]

Explanation 0

Two pushes yield None results, pop returns the last pushed value 20.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.