LLD Data Structures in Design Context: Stack — Understanding Last In, First Out Through Design
"A Stack isn't designed to store data. It's designed to make the most recent piece of work the easiest to access." In the previous article, we discovered a new kind of design problem. Some systems don't need to find the fastest item. Some don't need to process tasks in arrival order. Instead, they need to work with whatever happened most recently . That's exactly the problem a Stack solves. In this article, we'll understand how a Stack works and why its behavior appears naturally in many software systems. Imagine a Stack of Plates Think about a stack of dinner plates. Plate 4 ────────── Plate 3 ────────── Plate 2 ────────── Plate 1 ────────── When you need a plate, which one do you take? The one on the top. You don't pull out the bottom plate. Likewise, when placing a new plate, you put it on top. This simple rule defines the behavior of a Stack. What Is a Stack? A Stack is a data structure where both insertion and removal happen from the same end. The last item added is always the first one removed. This behavior is called LIFO (Last In, First Out). Push A ↓ Push B ↓ Push C ↓ Pop ↓ C Notice something important. A Stack isn't trying to preserve arrival order like a Queue. Instead, it preserves recency . The newest item is always the easiest to access. Every Data Structure Solves a Different Design Problem By now, we've seen several data structures, each answering a different question. A HashMap asks: Where is this object? A Heap asks: Which item has the highest priority? A Queue asks: Which task has been waiting the longest? A Stack asks: What happened most recently? Choosing the right data structure begins with identifying which of these questions your system needs to answer. Push and Pop Stacks are built around two simple operations. Push Adding a new item. Before Top ↓ B ↓ A Push C After Top ↓ C ↓ B ↓ A Pop Removing the most recent item. Before Top ↓ C ↓ B ↓ A Pop After Top ↓ B ↓ A Only the top item is removed. Everything below remains untouched. Real-World Examp