Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
Prashant Basnet, a software engineer at Unisala.com, focuses on software development and enjoys building platforms to share knowledge. Interested in system design, data structures, and is currently learning NLP
Arrays are where we start as devs. But what if I told you arrays secretly stack superpowers?
1. Arrays: Where It All Begins
Arrays are simple ordered lists, but processing them often leads to O(n²) nested loops.
Brute Force: For every element, scan right until you find a larger one → O(n²).
2. Stacks: The First Power-Up 🧙♂️
When we stack books like:
Core ops:
Stacks are simple. Stacks are just LIFO structures. But it can be more than that:
3. Monotonic Stacks: Sorted Stack
Think of organising nested bowls in your kitchen. Each new bowl must fit inside the previous one.
🔹 Use case: Next Smaller Element
💡 We pop until the current element is smaller than the top, then push.
Imagine people lining up for a photo, but there’s a rule:
🔹 Use case: Next Greater Element
💡 We pop until the stack top is larger than the incoming celeb, then push.
Types:
📈 Increasing stack (bottom→top): [1, 3, 5] → used for next smaller
📉 Decreasing stack: [7, 4, 2] → used for next greater
Stacks are powerful — they solve "next greater/smaller" problems in O(n).
But they have one blind spot:
⛔ They can’t adapt to moving windows or dynamic ranges.
⚠️ Why?
4. 📦 Queue (FIFO): First-In-First-Out
Think of people lining up to buy coffee:
Core ops:
📌 Use Case: Breadth-First Search (BFS), scheduling tasks, stream processing
5. Deque (Double-Ended Queue 🚪)
Now imagine a line where people can enter or exit from either end like a room with two doors.
That’s a deque:
You can maintain ordered windows of elements, dynamically adding/removing from both ends.
6 . Deque + Monotonicity
Building deque logic is the same as stack. In both, you maintain monotonic order by popping elements that violate the desired pattern.
Stacks are amazing when working with static arrays.
A deque lets you:
You Unlock a Power Weapon of data structure.
A simple analogy imagine you’re watching a group of influencers trying to stay trending on a live ranking board that updates every minute.
a. Sliding Window Max/Min in O(n)
b. Live Range Queries: Perfect for real-time analytics like:
c. Optimized Greedy & DP: Enables efficient subarray calculations like:
Leetcode Question:
🧱 Regular Stack Problems (LIFO)
📈 Monotonic Increasing Stack Problems
📉 Monotonic Decreasing Stack Problems
🚪 Monotonic Deque + Sliding Window