Visual Problem Solved with Monotonic Stack

🧱 𝗜 𝗦𝗼𝗹𝘃𝗲𝗱 𝗮 “𝗩𝗶𝘀𝘂𝗮𝗹” 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗨𝘀𝗶𝗻𝗴 𝗢𝗻𝗹𝘆 𝗮 𝗦𝘁𝗮𝗰𝗸 — 𝗡𝗼 𝗚𝗲𝗼𝗺𝗲𝘁𝗿𝘆 𝗡𝗲𝗲𝗱𝗲𝗱 Today’s problem looked visual and innocent: 𝗚𝗶𝘃𝗲𝗻 𝗯𝗮𝗿 𝗵𝗲𝗶𝗴𝗵𝘁𝘀 𝗼𝗳 𝗮 𝗵𝗶𝘀𝘁𝗼𝗴𝗿𝗮𝗺 (𝘄𝗶𝗱𝘁𝗵 = 𝟭), 𝗳𝗶𝗻𝗱 𝘁𝗵𝗲 𝗹𝗮𝗿𝗴𝗲𝘀𝘁 𝗿𝗲𝗰𝘁𝗮𝗻𝗴𝗹𝗲 𝗮𝗿𝗲𝗮. This is the classic problem from 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 — and it’s a beautiful lesson in how 𝗺𝗼𝗻𝗼𝘁𝗼𝗻𝗶𝗰 𝘀𝘁𝗮𝗰𝗸𝘀 𝗰𝗼𝗻𝘃𝗲𝗿𝘁 𝗴𝗲𝗼𝗺𝗲𝘁𝗿𝘆 𝗶𝗻𝘁𝗼 𝗶𝗻𝗱𝗶𝗰𝗲𝘀. 🧠 𝗧𝗵𝗲 𝗡𝗮𝗶𝘃𝗲 𝗧𝗵𝗼𝘂𝗴𝗵𝘁 (𝗮𝗻𝗱 𝘄𝗵𝘆 𝗶𝘁 𝗳𝗮𝗶𝗹𝘀) For every bar i, try expanding left and right until you hit a smaller bar. That’s O(n) per index -> O(n²). Too slow for n=10^5. So the real question becomes: For each bar, how far can it extend without hitting a smaller height? That is the entire problem. 💡 𝗞𝗲𝘆 𝗜𝗱𝗲𝗮 — 𝗡𝗲𝗮𝗿𝗲𝘀𝘁 𝗦𝗺𝗮𝗹𝗹𝗲𝗿 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 For every index i: 1. Find the first smaller bar on the left 2. Find the first smaller bar on the right A monotonic increasing stack gives both in linear time. ▶️ 𝗟𝗲𝗳𝘁 𝗦𝗰𝗮𝗻 (𝗟 -> 𝗥) Pop until the top is strictly smaller. That index defines the left boundary. ◀️ 𝗥𝗶𝗴𝗵𝘁 𝗦𝗰𝗮𝗻 (𝗥 -> 𝗟) Same logic to get the right boundary. Now each bar knows the exact range where it is the minimum. ⏱️ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 Each index pushed/popped once → O(n) Space → O(n) ✨ 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀 1. “Nearest smaller element” is a powerful pattern 2. Monotonic stacks turn nested loops into linear scans 3. Think: If this bar is the minimum, how wide can the rectangle be? A visual problem, solved with clean stack discipline. #DataStructures #Algorithms #MonotonicStack #Java #ProblemSolving #CodingInterview #Stack #DSA #LeetCode #Coding #Programmer #SoftwareEngineer #InterviewPrep #CompetitiveProgramming #100DaysOfCode #Tech #Learning #ProblemSolvingSkills

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories