Surface Area of 3D Shapes — LeetCode 892 Python Solution

EasyGeometryArrayMathMatrix
Problem
#892
Reading time
2 min

The problem

You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).

Example

Input
grid = [[1,2],[3,4]]
Output
34

Python solution

Python
class Solution:
    def surfaceArea(self, grid: List[List[int]]) -> int:
        ans = 0
        for i, row in enumerate(grid):
            for j, v in enumerate(row):
                if v:
                    ans += 2 + v * 4
                    if i:
                        ans -= min(v, grid[i - 1][j]) * 2
                    if j:
                        ans -= min(v, grid[i][j - 1]) * 2
        return ans

Complexity

MeasureComplexity
TimeO(n) or O(1)
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 892. Surface Area of 3D Shapes is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 892. Surface Area of 3D Shapes?
LeetCode 892. Surface Area of 3D Shapes is rated Easy on LeetCode.
What topics does LeetCode 892. Surface Area of 3D Shapes cover?
LeetCode 892. Surface Area of 3D Shapes is tagged Geometry, Array, Math and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview