Projection Area of 3D Shapes - Problem

You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.

Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).

We view the projection of these cubes onto the xy, yz, and zx planes. A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side.

Return the total area of all three projections.

Input & Output

Example 1 — Basic 2x2 Grid
$ Input: grid = [[1,2],[3,1]]
Output: 14
💡 Note: XY projection (top view): 4 non-zero cells. YZ projection (front view): max(1,2) + max(3,1) = 2 + 3 = 5. ZX projection (side view): max(1,3) + max(2,1) = 3 + 2 = 5. Total = 4 + 5 + 5 = 14.
Example 2 — Single Row
$ Input: grid = [[2]]
Output: 5
💡 Note: XY projection: 1 non-zero cell. YZ projection: max height in row = 2. ZX projection: max height in column = 2. Total = 1 + 2 + 2 = 5.
Example 3 — With Zero Heights
$ Input: grid = [[1,0],[0,2]]
Output: 8
💡 Note: XY projection: 2 non-zero cells. YZ projection: max(1,0) + max(0,2) = 1 + 2 = 3. ZX projection: max(1,0) + max(0,2) = 1 + 2 = 3. Total = 2 + 3 + 3 = 8.

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 50
  • 0 ≤ grid[i][j] ≤ 50

Visualization

Tap to expand
Projection Area of 3D Shapes INPUT grid = [[1,2],[3,1]] i=0 i=1 j=0 j=1 1 2 3 1 grid[0] = [1, 2] grid[1] = [3, 1] ALGORITHM STEPS 1 XY Projection (Top) Count non-zero cells = 4 cells 2 YZ Projection (Front) Max height per row max(1,2) + max(3,1) = 2+3 = 5 3 ZX Projection (Side) Max height per column max(1,3) + max(2,1) = 3+2 = 5 4 Sum All Projections Total = XY + YZ + ZX = 4 + 5 + 5 = 14 Top=4 Front=5 Side=5 FINAL RESULT Total Projection Area XY (Top) 4 + YZ (Front) 5 + ZX (Side) 5 = 14 Output: 14 - OK 4 + 5 + 5 = 14 Single pass: O(n^2) Key Insight: The XY projection counts all non-zero cells. The YZ projection sums the maximum values in each ROW. The ZX projection sums the maximum values in each COLUMN. All three can be computed in a single pass through the grid by tracking row/column maximums while iterating. TutorialsPoint - Projection Area of 3D Shapes | Single Pass Optimization
Asked in
Amazon 15 Google 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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