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] = [lefti, sideLengthi]
represents the ith
square with a side length of sideLengthi
that is dropped with its left edge aligned with X-coordinate lefti
.
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 ith
square.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using intervals
When a square is dropped onto the X-axis:
- It will either land directly on the X-axis if there are no overlapping squares below it.
- It will stack on top of an existing square if its position overlaps another square’s position vertically.
To solve this problem, we’ll maintain:
- A running record of intervals representing landed squares where each interval denotes the range
[lefti, lefti + sideLengthi]
and its corresponding height. - For each square being dropped, we’ll compute the new height based on the overlapping intervals and update the running record.
Approach
- Initialisation: Define an empty list to store the intervals and their heights, and an empty result list
ans
to store the tallest stack height after each square is dropped. - Iterate through each square in
positions
:- Extract the current square’s
left
andsideLength
. - Determine the height from overlapping intervals using a sweep for intervals and find the maximum vertical height beneath the square.
- Update the result list
ans
with the tallest stack height after adding the new square. - Update the intervals list with the current square’s position and new height.
- Extract the current square’s
- Return the result list
ans
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
. The outer loop iterates overpositions
, which hasn
elements.- For each square, we iterate over the existing intervals to check overlap, which can also be
n
in the worst case.
- For each square, we iterate over the existing intervals to check overlap, which can also be
- 🧺 Space complexity:
O(n)
. We maintain the list of intervals with up ton
entries, each storing[left, right, height]
.