Falling Squares - Problem

There are several squares being dropped onto the X-axis of a 2D plane. You are given a 2D integer array positions where positions[i] = [left_i, sideLength_i] represents the i-th square with a side length of sideLength_i that is dropped with its left edge aligned with X-coordinate left_i.

Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.

After each square is dropped, you must record the height of the current tallest stack of squares. Return an integer array ans where ans[i] represents the height described above after dropping the i-th square.

Input & Output

Example 1 — Basic Falling Squares
$ Input: positions = [[1,2],[2,3],[6,1]]
Output: [2,5,5]
💡 Note: Square 1: [1,2] lands on ground, height = 2, max = 2. Square 2: [2,3] overlaps with Square 1, lands at height 2, new height = 2+3 = 5, max = 5. Square 3: [6,1] no overlap, lands on ground, height = 1, max = 5.
Example 2 — Stacking High
$ Input: positions = [[0,2],[1,2]]
Output: [2,4]
💡 Note: Square 1: [0,2] lands on ground, height = 2. Square 2: [1,2] overlaps Square 1 (range [1,3] overlaps [0,2]), lands on top, height = 2+2 = 4.
Example 3 — No Overlaps
$ Input: positions = [[0,1],[2,1],[4,1]]
Output: [1,1,1]
💡 Note: All squares land on ground separately with no overlaps. Each has height 1, so maximum remains 1.

Constraints

  • 1 ≤ positions.length ≤ 1000
  • 1 ≤ lefti ≤ 108
  • 1 ≤ sideLengthi ≤ 106

Visualization

Tap to expand
Falling Squares: Visual SimulationX-axis (ground level)Square 1pos=1, size=2height: 2Square 2pos=2, size=3lands on Square 1Sq3pos=6, size=1on groundInput: [[1,2], [2,3], [6,1]]Output: [2, 5, 5]After square 1: max height = 2After square 2: max height = 2 + 3 = 5After square 3: max height = 5 (unchanged)
Understanding the Visualization
1
Input
Array of [position, size] for each square
2
Process
Drop squares one by one, they stack on overlapping squares
3
Output
Height of tallest stack after each drop
Key Takeaway
🎯 Key Insight: Track the maximum height efficiently by finding overlaps and stacking squares on the highest overlapping base
Asked in
Google 25 Amazon 20 Facebook 15
18.5K Views
Medium Frequency
~35 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen