09 Sept 2026Go / Python / TypeScriptEasy

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
  • Python surface-area-of-3d-shapes/solution.py
  • TypeScript surface-area-of-3d-shapes/solution.ts

Solution files

Gosurface-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
}
Pythonsurface-area-of-3d-shapes/solution.py
class Solution:
    def surfaceArea(self, grid: list[list[int]]) -> int:
        area = class="syntax-number">0
        for row in range(len(grid)):
            for column in range(len(grid[class="syntax-number">0])):
                height = grid[row][column]
                if not height: continue
                area += class="syntax-number">2 + class="syntax-number">4 * height
                if row: area -= class="syntax-number">2 * min(height, grid[row - class="syntax-number">1][column])
                if column: area -= class="syntax-number">2 * min(height, grid[row][column - class="syntax-number">1])
        return area
TypeScriptsurface-area-of-3d-shapes/solution.ts
function surfaceArea(grid: number[][]): number {
  let area = class="syntax-number">0;
  for (let row = class="syntax-number">0; row < grid.length; row += class="syntax-number">1) for (let column = class="syntax-number">0; column < grid[class="syntax-number">0].length; column += class="syntax-number">1) { const height = grid[row][column]; if (height === class="syntax-number">0) continue; area += class="syntax-number">2 + class="syntax-number">4 * height; if (row > class="syntax-number">0) area -= class="syntax-number">2 * Math.min(height, grid[row - class="syntax-number">1][column]); if (column > class="syntax-number">0) area -= class="syntax-number">2 * Math.min(height, grid[row][column - class="syntax-number">1]); }
  return area;
}