Spread the word.

Share the link on social media.

Share
  • Facebook
Have an account? Sign In Now

Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Home/Questions/Q 3519
Next
In Process

RTSALL Latest Articles

abderahman
abderahman
Asked: September 11, 20262026-09-11T09:51:17-05:00 2026-09-11T09:51:17-05:00In: Data Structures & Algorithms, Stacks, Queues & Ring Buffers

How does a Monotonic Stack solve Largest Rectangle in Histogram in a single pass?

I understand how to solve the Largest Rectangle in Histogram in O(N^2) by expanding left and right from every bar. But top interviewers and competitive programming platforms always expect the O(N) single-pass Monotonic Stack solution.

Every explanation I read online just dumps a while loop with stack pops without clearly explaining why the stack width formula i - stack[-1] - 1 works. Can someone break down the exact mental model like I’m a junior engineer?

  • 0
  • 2 2 Answers
  • 0 Followers
  • 0
  • Share
    Share
    • Share on Facebook
    • Share on Twitter
    • Share on LinkedIn
    • Share on WhatsApp

Leave an answer
Cancel reply

You must login to add an answer.


Forgot Password?

Need An Account, Sign Up Here

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Abhay Tiwari
    Abhay Tiwari Begginer
    2026-09-11T09:51:19-05:00Added an answer on September 11, 2026 at 9:51 am

    The Largest Rectangle in Histogram is famous because it feels like magic until you see the visual geometry behind it. Let’s demystify it once and for all.

    1. The Core Realization

    For any bar at index k with height H = heights[k], what is the widest rectangle you can make using H as the height?

    The rectangle can extend as far left as possible until it hits a bar shorter than H, and as far right as possible until it hits another bar shorter than H.

    So the entire problem boils down to finding two things for every bar:

    1. The First Shorter Bar on the Left (left boundary).
    2. The First Shorter Bar on the Right (right boundary).

    2. Why a Monotonic Increasing Stack?

    A monotonic stack keeps indices of bars whose heights are strictly increasing: [2, 4, 6, 8].

    As long as the next bar is taller or equal, the rectangle could potentially keep growing, so we just push its index onto the stack.

    The Trigger: The moment you encounter a bar that is shorter than the top of the stack (say we see a bar of height 3 when the stack top is 8), you have found the Right Boundary for that 8! The bar of height 8 cannot extend any further to the right. Its journey is finished.

    When you pop 8:

    • The current index i is its first shorter bar on the right.
    • The new top of the stack (the element directly below it) is its first shorter bar on the left!

    Therefore, the width of the rectangle bounded by height H is simply: width = (i - stack[-1] - 1).


    3. Clean Python 3.12 Implementation with Sentinel Trick

    def largest_rectangle_area(heights: list[int]) -> int:
        """Calculates maximum rectangular area in histogram in O(N) time."""
        # Appending 0 at the end acts as a sentinel that forces
        # all remaining bars in the stack to be popped and calculated!
        extended_heights = heights + [0]
        stack: list[int] = []  # Stores indices
        max_area = 0
    
        for i, h in enumerate(extended_heights):
            # While the current bar is shorter than the bar at stack top
            while stack and extended_heights[stack[-1]] > h:
                height = extended_heights[stack.pop()]
                
                # If stack is empty, it means 'height' was shorter than everything to its left!
                width = i if not stack else i - stack[-1] - 1
                max_area = max(max_area, height * width)
                
            stack.append(i)
    
        return max_area
    

    4. Step-by-Step Trace with Numbers

    Let’s trace heights = [2, 1, 5, 6, 2, 3] with sentinel [2, 1, 5, 6, 2, 3, 0]:

    • i = 0 (h=2): Stack = [0]
    • i = 1 (h=1): 1 < 2! Pop 0 (h=2). Stack empty → width = 1. Area = 2 * 1 = 2. Push 1. Stack = [1].
    • i = 2 (h=5): 5 > 1. Push 2. Stack = [1, 2].
    • i = 3 (h=6): 6 > 5. Push 3. Stack = [1, 2, 3].
    • i = 4 (h=2): 2 < 6!
      • Pop 3 (h=6): right = 4, left = 2 → width = 4 - 2 - 1 = 1. Area = 6 * 1 = 6.
      • Pop 2 (h=5): right = 4, left = 1 → width = 4 - 1 - 1 = 2. Area = 5 * 2 = 10!

      Push 4. Stack = [1, 4].

    • Finally, the trailing 0 sentinel cleanly flushes all remaining elements.

    Max Area = 10 (from bars of height 5 and 6).


    5. Why is this strictly O(N)?

    Even though there is a while loop inside the for loop, every index is pushed onto the stack exactly once and popped from the stack at most once. Total operations across the entire array are at most 2N. That is a rock-solid, linear O(N) runtime with O(N) memory.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Anonymous
    Anonymous Begginer
    2026-09-11T21:26:34-05:00Added an answer on September 11, 2026 at 9:26 pm

    Here is the C++20 Single-Pass Monotonic Stack solution. We reserve memory on the stack vector upfront to eliminate dynamic reallocation pauses.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <cstdint>
    
    int64_t largestRectangleArea(std::vector<int>& heights) {
        // Append 0 sentinel to flush all remaining elements at the end
        heights.push_back(0);
        const size_t n = heights.size();
        std::vector<int> stack;
        stack.reserve(n);
        int64_t max_area = 0;
    
        for (int i = 0; i < (int)n; ++i) {
            while (!stack.empty() && heights[stack.back()] > heights[i]) {
                int64_t h = heights[stack.back()];
                stack.pop_back();
    
                int64_t width = stack.empty() ? i : (i - stack.back() - 1);
                max_area = std::max(max_area, h * width);
            }
            stack.push_back(i);
        }
        return max_area;
    }
    
    int main() {
        std::vector<int> bars = {2, 1, 5, 6, 2, 3};
        std::cout << "Largest Rectangle Area: " << largestRectangleArea(bars) << "n";
        return 0;
    }
    

    Performance: Using std::vector::reserve() guarantees zero heap reallocations during stack operations.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp

Sidebar

Ask A Question
  • Popular
  • Answers
  • Queryiest

    What is a database?

    • 3 Answers
  • Anonymous

    How to rotate an array in-place with O(1) space and ...

    • 3 Answers
  • hannah

    What steps can businesses take to identify the most valuable ...

    • 2 Answers
  • Vikram
    aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
  • Abhishek
    Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
  • Sneha Patel
    Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

Related Questions

  • pgvector: HNSW index build fails with out-of-memory or high swap: ...

    • 1 Answer
  • Why does std::views::filter on temporary containers trigger undefined behavior and ...

    • 1 Answer
  • PyTorch RuntimeError: CUDA out of memory: Why torch.cuda.empty_cache() fails & ...

    • 1 Answer
  • Next.js 15: Error: Route used "params" without awaiting it (Asynchronous ...

    • 1 Answer
  • Task Scheduler with Cooldowns: Closed-form mathematical formula vs Priority Queue ...

    • 2 Answers

Top Members

Queryiest

Queryiest

  • 201 Questions
  • 295 Points
Enlightened
Anonymous

Anonymous

  • 11 Questions
  • 42 Points
Begginer
paperubofficial

paperubofficial

  • 0 Questions
  • 22 Points
Begginer

Trending Tags

ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • DSA Problems
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

Footer

About Us

  • Meet The Team
  • Blog
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Help

  • Knowledge Base
  • Support

Follow

© 2023-25 RTSALL. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.