↓Skip to main content
  1. LeetCode/

LeetCode 883: Projection Area of 3D Shapes

·1 min· ·
LeetCode Easy Array Math Geometry Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-21

  • Submissions: Runtime Error ×4 → Wrong Answer ×2 → Accepted

Approach
#

The three projections (Matrix Template 3):

  • From above: each cell with grid[i][j] > 0 contributes 1.
  • From the front: the tallest stack in each column.
  • From the side: the tallest stack in each row.

My Attempts
#

The first attempts were variable and type REs. The next two joined every number into one string and counted '0' characters to subtract empty cells, but once any cell is empty, the '0' inside numbers such as 10 and 20 is counted too: [[0, 10]] should be 21; it returned 20. Testing grid[i][j] > 0 passed.

Solution
#

class Solution:
    def projectionArea(self, grid: List[List[int]]) -> int:
        top = sum(v > 0 for row in grid for v in row)
        side = sum(max(row) for row in grid)
        front = sum(max(col) for col in zip(*grid))
        return top + side + front

Complexity
#

Time O(n²), space O(1).

Mistakes to Avoid
#

  • The top view counts nonzero cells; do not count '0' characters in a string.

Interview Explanation
#

The top view is the number of nonzero cells, and the front and side views sum the maxima of the columns and rows; I add all three. Time O(n²).

Related

LeetCode 812: Largest Triangle Area
·2 mins
LeetCode Easy Array Math Geometry Polygons
LeetCode 812 note: with at most 50 points, enumerate every triple and take the largest shoelace area
LeetCode 867: Transpose Matrix
·1 min
LeetCode Easy Array Matrix Simulation
LeetCode 867 note: the transpose is n × m with res[j][i] = matrix[i][j]; in Python, zip(*matrix)
LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 836: Rectangle Overlap
·2 mins
LeetCode Easy Math Geometry
LeetCode 836 note: two rectangles overlap exactly when their x intervals and y intervals both overlap, i.e. min(right) > max(left)
LeetCode 766: Toeplitz Matrix
·2 mins
LeetCode Easy Array Matrix
LeetCode 766 note: every diagonal is constant exactly when each cell equals its upper-left neighbor
LeetCode 733: Flood Fill
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 733 note: DFS or BFS from the start, recoloring 4-directional cells that share the start’s original color; return immediately if the colors are equal