Isaac Emmanuel
09 Sept 2026•EasyGo / Python / TypeScript

Surface Area of 3D Shapes

Compute the exposed surface area of vertical cube stacks arranged on a grid.

Add top, bottom, and four sides for each nonempty stack, then subtract the hidden faces shared with the stack above and to the left.

Complexity

O(rows * columns) time and O(1) space.

Solution files

Go•surface-area-of-3d-shapes/solution.go
package main

func surfaceArea(grid [][]int) int {
	area := 0
	for row := range grid {
		for column, height := range grid[row] {
			if height == 0 {
				continue
			}
			area += 2 + 4*height
			if row > 0 {
				area -= 2 * minimumSurface(height, grid[row-1][column])
			}
			if column > 0 {
				area -= 2 * minimumSurface(height, grid[row][column-1])
			}
		}
	}
	return area
}
func minimumSurface(a int, b int) int {
	if a < b {
		return a
	}
	return b
}
Python•surface-area-of-3d-shapes/solution.py
class Solution:
    def surfaceArea(self, grid: list[list[int]]) -> int:
        area = 0
        for row in range(len(grid)):
            for column in range(len(grid[0])):
                height = grid[row][column]
                if not height: continue
                area += 2 + 4 * height
                if row: area -= 2 * min(height, grid[row - 1][column])
                if column: area -= 2 * min(height, grid[row][column - 1])
        return area
TypeScript•surface-area-of-3d-shapes/solution.ts
function surfaceArea(grid: number[][]): number {
  let area = 0;
  for (let row = 0; row < grid.length; row += 1) for (let column = 0; column < grid[0].length; column += 1) { const height = grid[row][column]; if (height === 0) continue; area += 2 + 4 * height; if (row > 0) area -= 2 * Math.min(height, grid[row - 1][column]); if (column > 0) area -= 2 * Math.min(height, grid[row][column - 1]); }
  return area;
}