#699

Falling Squares

Hard Segment tree with range assign / range max

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Squares fall one by one onto a line; each lands on top of the highest square under its span. After each drop, report the tallest stack height so far.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: drop squares one by one; report the tallest stack after each drop.

Why this works: a segment tree over compressed x-coordinates answers "max height in a range" and "set a range to h".

Example: [[1,2], [2,3], [6,1]]

square 1 lands at 0 → height 2square 2 overlaps → 2 + 3 = 5square 3 alone → 1 → answers [2, 5, 5]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Treating the right edge as occupied — squares touching at an edge don't stack, so use the half-open range [left, left + side).

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Segment Tree, Fenwick & Sparse Table
🎬 Episodes 98–100: video coming soon