C++ 0699.cpp
class Solution {
public:
vector<int> fallingSquares(vector<vector<int>>& positions) {
map<int, int> height;
height[0] = 0; // ground plane
int highest = 0;
vector<int> result;
for (auto p : positions)
{
auto x1 = p[0];
auto x2 = x1 + p[1];
auto y = p[1];
// directly below
auto l = height.upper_bound(x1);
auto r = height.lower_bound(x2);
// highest square
auto peak = prev(l)->second;
auto last = peak;
for (auto scan = l; scan != r; scan++)
{
peak = max(peak, scan->second);
last = scan->second;
}
// overwrite them
if (l != r)
height.erase(l, r);
height[x1] = peak + y; // left up
if (height.count(x2) == 0) // right down
height[x2] = last;
highest = max(highest, peak + y);
result.push_back(highest);
}
return result;
}
};
Difficulty
and has an acceptance rate of about 48% (70k+ submissions).
Typical patterns to solve this problem:
- Array
- Ordered Set
- Segment Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the “falling squares” problem by maintaining a map that records the height of the skyline at critical x-coordinates. Each square is processed sequentially; the map is queried to find the maximum height under the new square’s interval, the skyline is updated to reflect the added height, and the global maximum height so far is recorded. The result vector contains the running maximum after each insertion.
Key Steps
Initialisation
map<int, int> height;
height[0] = 0; // ground plane
int highest = 0;
vector<int> result;
A std::map named height stores pairs (x-coordinate, current height). The entry (0,0) represents the ground level at the far left. highest tracks the overall tallest stack, while result will accumulate the answer.
Iterating Over Squares
for (auto p : positions)
{
auto x1 = p[0];
auto x2 = x1 + p[1];
auto y = p[1];
…
}
For each square the left edge x1, right edge x2, and side length y are extracted. The interval [x1, x2) is the horizontal span that will be affected.
Locating Affected Skyline Segments
auto l = height.upper_bound(x1);
auto r = height.lower_bound(x2);
l points to the first map entry whose key is greater than x1; r points to the first entry whose key is not less than x2. The range [l, r) therefore covers all existing critical points that lie strictly inside the new square’s interval.
Determining the Base Height
auto peak = prev(l)->second;
auto last = peak;
for (auto scan = l; scan != r; scan++)
{
peak = max(peak, scan->second);
last = scan->second;
}
prev(l) yields the height just to the left of x1, which serves as the initial base. The loop scans every critical point inside the interval, updating peak to the highest existing height encountered. last ends up holding the height at the rightmost scanned point, which is needed later to preserve the skyline beyond x2.
Updating the Skyline
if (l != r)
height.erase(l, r);
height[x1] = peak + y; // left up
if (height.count(x2) == 0) // right down
height[x2] = last;
All map entries that fall inside the interval are removed, collapsing the region into a single new segment. The left boundary x1 receives the new height peak + y. If there is no existing entry at x2, a right-boundary entry is inserted with height last, ensuring the skyline continues correctly beyond the square.
Recording the Global Maximum
highest = max(highest, peak + y);
result.push_back(highest);
After the square lands, the overall tallest stack is possibly increased. The current highest value is appended to result.
Edge Cases Handled
When a new square starts exactly at an existing critical point, upper_bound(x1) returns the iterator to the next point, while prev(l) still gives the height at x1. This correctly treats the left edge as sharing the existing height.
If the square’s interval does not intersect any existing interior points (l == r), the erase step is skipped and only the left boundary entry is added. The right boundary entry is created only when absent, preserving any previously stored height at that coordinate.
When a square completely covers the current skyline (e.g., it is the first or it spans all existing keys), the loop still computes peak from the left neighbor and last from the rightmost scanned point, guaranteeing that the new height is applied uniformly across the whole interval.
The map always contains a sentinel entry at 0, so prev(l) is safe even when x1 is the smallest key.
Performance Optimizations
The use of an ordered std::map provides logarithmic access to neighboring keys, allowing the algorithm to locate the relevant interval boundaries with upper_bound and lower_bound. By erasing the entire range [l, r) in a single call, the code avoids repeated deletions and rebalancing of the tree, which would be more costly.
Storing only critical points (where the height changes) keeps the map size proportional to the number of distinct edges introduced by the squares, rather than to the total width of the coordinate space. This sparse representation reduces both memory usage and the number of iterations needed to compute peak.
The loop that scans the affected segment updates peak and last in one pass, eliminating the need for a separate pass to compute the maximum height.
Finally, the global maximum highest is maintained incrementally, so the result vector can be filled without a secondary traversal of the map after all squares are processed.
ELI5 - Simplified Explanation
Imagine you have a flat floor and you are building a tower made of colorful square blocks. Every time you drop a new square, it falls down until it hits something.
The code starts by remembering that the floor is flat at zero. Each square has a starting position where it lands and a width that tells how big it is. To figure out where the square stops, the computer looks at the ground underneath it to see the highest point that square touches.
It draws a line from the start of the square to the end of the square. It checks all the little areas underneath that span to see which one is the tallest. Once it finds the highest spot, it places the new square right on top of that height.
Because the new square covers up the old floor or previous blocks, the computer updates its list to show the new shapes. If the square hangs off the edge, it remembers the height of the floor next to it. After placing the block, it looks at the very top of the new square to see if it is now the tallest thing built so far. It keeps track of the tallest height after every single block drop and writes those down on a list.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++ | Java | Go | Python | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 218: The Skyline Problem
Solved On The Same Day
- problem 464: Can I Win
- problem 729: My Calendar I
- problem 1286: Iterator for Combination
- problem 1348: Tweet Counts Per Frequency
- problem 1387: Sort Integers by The Power Value
- problem 2424: Longest Uploaded Prefix
- problem 327: Count of Range Sum
- problem 1553: Minimum Number of Days to Eat N Oranges
- problem 1611: Minimum One Bit Operations to Make Integers Zero
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality