DDSA Solutions

892. Surface Area of 3D Shapes

Time: O(n²)
Space: O(1)
Advertisement

Intuition

Each stack of h cubes: top and bottom faces plus 4 sides minus shared internal faces. Adjacent stacks reduce area by 2*min(h1,h2).

Algorithm

  1. 1For each cell with h>0: add 2 + 4*h.
  2. 2For each adjacent cell pair: subtract 2*min(h1,h2).

Common Pitfalls

  • Count both top and bottom (2), plus 4*h sides, minus internal vertically stacked faces already handled by 4h+2 formula.
892.cs
C#
// Approach: Per cell contribute 4·h+2 faces; subtract 2·min(h, neighbor) for each shared wall with adjacent cells.
// Time: O(n²) Space: O(1)

public class Solution
{
    public int SurfaceArea(int[][] grid)
    {
        int ans = 0;
        int n = grid.Length;

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] > 0)
                    ans += grid[i][j] * 4 + 2;

                if (i > 0)
                    ans -= Math.Min(grid[i][j], grid[i - 1][j]) * 2;

                if (j > 0)
                    ans -= Math.Min(grid[i][j], grid[i][j - 1]) * 2;
            }
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?