KatInterview

Largest Rectangle Under a Skyline with Forbidden Zones

Stacks & QueuesAuto-graded · 17 test cases
HardAuto-gradedStacks & Queuesmonotonic stackarraysgeometry

Last updated

Tests the ability to apply a monotonic stack to find the largest rectangular area under a histogram while skipping columns that are marked as forbidden.

Largest Rectangle Under a Skyline with Forbidden Zones

You are given the elevation profile of a city skyline as a list of non-negative integer heights, one per column. Each column has unit width. Additionally, some columns are forbidden: a rectangle may not include any forbidden column, even partially.

Your task is to find the area of the largest axis-aligned rectangle that:

  1. Fits entirely under the skyline (its height at every included column does not exceed that column's height), and
  2. Spans only a contiguous block of columns, none of which are forbidden.

A rectangle spanning columns l through r (inclusive) has area (r - l + 1) * min(heights[l..r]).

Return the maximum such area. If no valid rectangle exists (e.g., all columns are forbidden or all heights are zero), return 0.

Constraints

  • 1 <= len(heights) == len(forbidden) <= 2000
  • 0 <= heights[i] <= 10^6
  • forbidden[i] is 0 (allowed) or 1 (forbidden)
  • A rectangle must span at least one non-forbidden column with height > 0 to have positive area.
  • The answer fits in a standard Python int.

Examples

Example 1

Input: largest_skyline_rectangle([3, 1, 3, 3, 2], [0, 0, 0, 0, 0])

Output: 6

Example 2

Input: largest_skyline_rectangle([4, 2, 0, 3, 5, 1], [0, 0, 1, 0, 0, 0])

Output: 6

Example 3

Input: largest_skyline_rectangle([5, 5, 5, 5], [1, 1, 1, 1])

Output: 0

Hints

Hint 1

Split the column array into maximal contiguous runs of non-forbidden columns, then solve each run independently.

Hint 2

Within each non-forbidden run, the classic largest-rectangle-in-histogram algorithm using a monotonic (non-decreasing) stack runs in O(n) time.

Hint 3

When you pop a bar from the stack to compute its candidate area, the width extends from the element now on top of the stack (exclusive) to the current index (exclusive), capped by the run boundaries.