Stacks and Monotonic Structures
36 / 170Stacks and Monotonic StructuresLesson 6 of 8About 53 min
The hardest stack problem in the set, and it is the span formula you already wrote.
Given bars of varying heights standing side by side, find the largest rectangle that fits inside them. The rectangle may span several bars and is limited by the shortest bar it covers.
Trying every pair of endpoints is O(n squared). The reframe is to stop thinking about rectangles and think about bars: every candidate rectangle has some shortest bar, so it is enough to ask, for each bar, what is the widest rectangle whose height is exactly that bar.
Time and space for largest_rectangle_two_pass on n bars.
previous_smaller = [-1] * nstack = []for i in range(n): while stack and heights[stack[-1]] >= heights[i]: stack.pop() previous_smaller[i] = stack[-1] if stack else -1 stack.append(i)Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.