Python 0883.py
class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
xy = set()
xz = set()
yz = set()
for y in range(len(grid)):
for x in range(len(grid[y])):
height = grid[y][x]
for z in range(height):
xy.add((x, y))
xz.add((x, z))
yz.add((y, z))
return len(xy) + len(xz) + len(yz)
Difficulty
and has an acceptance rate of about 73% (70k+ submissions).
Typical patterns to solve this problem:
- Array
- Geometry
- Math
- Matrix
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 provided Solution class implements a method projectionArea that computes the total area of the three orthogonal projections (onto the xy-plane, xz-plane, and yz-plane) of a solid built from unit cubes. The solid is described by a two-dimensional list grid where each entry specifies the stack height of cubes at that (x, y) coordinate. The algorithm translates the three-dimensional shape into three distinct sets of coordinate pairs, each representing one projection, and finally returns the sum of the unique positions in those sets.
Key Steps
Set Initialization
The method begins by creating three empty sets, one for each projection.
xy = set()
xz = set()
yz = set()
These sets will automatically enforce uniqueness, ensuring that overlapping cubes are counted only once per projection.
Traversal of the Input Grid
Two nested for loops iterate over the rows and columns of grid. The outer loop uses the variable y to index rows, while the inner loop uses x for columns.
for y in range(len(grid)):
for x in range(len(grid[y])):
height = grid[y][x]
By accessing len(grid[y]) for each row, the code gracefully handles rectangular grids where rows may have differing lengths.
Adding Projection Coordinates
For each cell, the algorithm examines the stack height. An inner loop runs from 0 up to height-1, adding a coordinate tuple to each set for every unit cube in the column.
for z in range(height):
xy.add((x, y))
xz.add((x, z))
yz.add((y, z))
- The tuple
(x, y)records the presence of a cube when projected onto the xy-plane. - The tuple
(x, z)records the projection onto the xz-plane, wherezdenotes the vertical level of the cube. - The tuple
(y, z)records the projection onto the yz-plane.
Because sets discard duplicate entries, multiple cubes that share the same projection coordinate contribute only once to the final area count.
Computing the Result
After processing the entire grid, the method returns the combined size of the three sets, which corresponds to the total projection area.
return len(xy) + len(xz) + len(yz)
Each len call yields the number of distinct cells visible in the respective projection.
Edge Cases Handled
When a cell contains a height of zero, the inner for z in range(height) loop does not execute, so no coordinates are added for that position. This correctly excludes empty columns from all projections.
If the input grid is empty (i.e., grid = []), the outer loop never runs, leaving all three sets empty. The final sum of lengths is zero, which accurately reflects that there is no solid to project.
The algorithm also accommodates non-square grids because the inner loop determines the column count per row dynamically with len(grid[y]). Consequently, rows of varying lengths are processed without error, and each valid cell contributes its appropriate projections.
Performance Optimizations
The primary optimization lies in the use of hash-based sets for each projection. Insertion into a set has average-case constant time, allowing the algorithm to deduplicate projection coordinates on the fly without requiring a secondary pass.
By storing only the minimal coordinate pairs needed for each view, the implementation avoids constructing a full three-dimensional representation of the solid, which would consume substantially more memory. The approach scales with the number of cubes actually present rather than the theoretical maximum volume defined by the grid dimensions.
The explicit iteration over z levels, while linear in the height of each column, ensures that each unit cube contributes exactly one entry per projection, preserving correctness while keeping the code straightforward and cache-friendly.
Overall, the method balances clarity with efficient use of data structures to achieve the desired projection area calculation.
ELI5 - Simplified Explanation
Imagine a collection of tall towers made out of colorful blocks standing on a flat board. The towers have different heights based on the numbers in the grid. This code acts like a sun shining from three different directions to see the shadows the towers cast.
First, the sun shines straight down from above. Every stack that has at least one block creates a shadow on the floor. That shadow is like a square on a map for every spot where a tower exists.
Next, the sun shines from the front of the board. All the tall towers block the light, so they create a long, stretched shadow on a wall behind them. The code looks at each row of towers to find the tallest one because that is the only part of the shadow that matters for this view.
Finally, the sun shines from the side of the board. This creates another shadow on a different wall. The code looks at all the towers in each column to find the tallest one so it knows how high that shadow reaches.
To finish the work, the code counts every single square in these three shadows. It collects all the little points where the shadows touch the floor and the walls, adds them all together, and finds the total number of shaded spots.
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++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Rust | Python | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 999: Available Captures for Rook
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