LeetCode Stock Span Problem Solution with Monotonic Stack

🔥 Day 94 of #100DaysOfCode Today’s problem: LeetCode – Online Stock Span 📈 📌 Problem Summary Design a class StockSpanner that calculates the stock span for each new price. 👉 The span of a stock’s price today is the number of consecutive days (including today) the price was less than or equal to today’s price. Example input: [100, 80, 60, 70, 60, 75, 85] Output: [1, 1, 1, 2, 1, 4, 6] 🧠 Approach: Monotonic Stack (Decreasing Stack) This is another powerful Next Greater Element pattern, but optimized for streaming input. Instead of storing just prices, we store: {price, span} ⚙️ Core Logic (in next(price)): 1️⃣ Initialize span = 1 2️⃣ While stack is not empty AND top price ≤ current price: Add popped span to current span 3️⃣ Push {price, span} into stack 4️⃣ Return span 💡 Why Store Span Instead of Index? Because: It compresses previous smaller values into one value. Avoids recalculating spans repeatedly. Makes each element pushed & popped only once. ⏱ Time Complexity: O(n) amortized Each price is pushed once and popped once. 💾 Space Complexity: O(n) 🚀 Performance Runtime: 30 ms Beats ~72% Clean and optimal solution ✔️ 🧠 Pattern Insight Problems like: Daily Temperatures Next Greater Element Stock Span 👉 All use Monotonic Stack Stack mastery getting stronger 🔥 On to Day 95 🚀 #100DaysOfCode #LeetCode #MonotonicStack #StockSpan #Java #DSA #InterviewPrep

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories