Squares are dropped one at a time onto a flat floor (the x-axis). positions[i] = [left, side] means square i has side length side and its left edge at x = left, so it covers x from left to left + side.
Each square falls straight down until it rests on the floor or on the top of a square below it. Squares that only touch side to side do not hold each other up. Once landed, a square never moves.
After each drop, record the height of the highest point of any stack so far. Return the list of those heights.
Example 1
Input: positions = [[1, 3], [3, 2], [6, 1]] Output: [3, 5, 5] Why: the second square lands on the first (3 + 2); the third is alone
2 more examples and the constraints
Example 2
Input: positions = [[5, 2], [7, 4]] Output: [2, 4] Why: the second only touches the first's right side, so it hits the floor
Example 3
Input: positions = [[4, 3], [4, 1]] Output: [3, 4] Why: the small square lands on top of the big one: 3 + 1
Constraints
- 1 ≤ length of positions ≤ 1,000
- 1 ≤ left ≤ 100,000,000
- 1 ≤ side ≤ 1,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every earlier squareO(n²)
- Coordinate compression + segment treeO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 squares | Verdict |
|---|---|---|---|
| Check every earlier square | O(n²) | Passes for n ≤ 1,000; simplest | |
| Coordinate compression + segment tree | O(n log n) | Best; scales to large n |
n = number of squares.
Edge cases to test
- Touching sides. [[5, 2], [7, 4]]: x = 7 is shared, but the second square still falls to the floor.
- Exact stack. Squares at the same left with the same side pile up: heights 2, 4, 6, ...
- Small square on a big one. [[4, 3], [4, 1]] gives [3, 4].
- Tallest never drops. A later short square far away keeps the answer at the old maximum.
- Huge stack. 1,000 squares of side 1,000,000 stacked give 1,000,000,000, which still fits a 32-bit int.
Common mistakes
- Using ≤ in the overlap test, so squares that only touch get stacked.
- Appending the new square's own top instead of the tallest stack so far.
- Landing on the most recent overlapping square instead of the highest one.
How to talk through it
- 1Clarify. Do squares touching only at an edge support each other? Is the answer the overall tallest after each drop?
- 2State the landing rule. A square rests on the highest top among the squares it truly overlaps.
- 3Code the O(n²) scan. Check every earlier square with strict inequalities; with n ≤ 1,000 it is enough.
- 4Scale it up. Compress the edges and use a segment tree for range max and range raise, O(n log n).
- 5Test out loud. Run the touching case and a stack of equal squares.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?