Beginner · INTERACTIVE LESSON

Stack

Push onto the top, peek without removing, and pop the last value added.

The interactive player is loading. If it does not appear, you can still read the explanation below.

THE IDEA BEHIND THE STEPS

How it works

A stack is last in, first out (LIFO). Push adds a value at the top, pop removes and returns the top value, and peek returns it without removing it. Try a sequence one operation per line. The top index is size minus one; -1 means empty. Item labels use the push operation number, so equal values remain distinct.

This lesson starts empty and uses a fixed array capacity of 1–16 slots for teaching. Values are whole numbers from -999 to 999; a sequence contains at most 32 operations. A successful push returns success. A full push reports overflow; empty pop and peek report underflow. Rejected operations leave the stack unchanged, and the next operation still runs. This capacity limit is not a rule that every real stack has only 16 items.

With a fixed array and a top index, push, pop and peek take O(1) best- and worst-case algorithm time. Allocated storage is O(C) for capacity C (often written O(n) when n denotes the maximum supported size); occupied items use O(k) for current size k. A dynamically resized array may instead give amortized O(1) push with an O(k) resizing operation. This simulator copies states and keeps result history for replay, which costs extra time and storage. Playback speed is not algorithm runtime.

Completed operations count includes rejected operations. Writes count one slot assignment for a successful push and one slot clear for a successful pop; peek and rejected operations write nothing. The check step shows the state before the operation; the result step shows its returned value and updated top. Reduced motion retains every state without movement.