A Stack is an abstract concept (an interface) that can be built using either an Array or a Linked List under the hood. Both implementations provide O(1) time complexity for Push and Pop operations.
Array Stack: A pill organizer box. Fixed number of slots. Fast to use, but when it's full, you need a new bigger box. Linked List Stack: A chain of paperclips. You can keep adding paperclips forever as long as you have more, but each paperclip has a bit of extra wire (memory overhead).
You can build a stack using Arrays or Linked Lists.
| Action | Speed |
|---|---|
| Push / Pop | O(1) |
| Search | O(n) |
Two Ways to Build a Stack
1. The Array Approach
You use an array to hold the elements and an integer variable called top to keep track of the index of the top element.
2. The Linked List Approach
Every time you push, you create a new Node and make it point to the old 'top'. Now this new Node is the top.
Performance (Time Complexity)
No matter which way you build it, Stacks are incredibly fast for what they do.
Understanding implementation choices helps you optimize your applications. Arrays are faster for caching but have fixed sizes. Linked lists consume slightly more memory per node but can grow dynamically without resizing costs.
"What is the time complexity of pushing an element onto a stack, and why?"
O(1) because you always insert exactly at the top pointer location. You do not need to shift any existing elements.