Leetcode 892. Surface Area of 3D Shapes
You are given an n x n
grid where we have n
vertical stacks of cubes. Each cell (i, j)
in the grid represents a vertical stack of cubes that has grid[i][j]
cubes.
Return the total surface area of the resulting shapes formed by these stacks.
n
x n
)?
1 <= n <= 50
.grid[i][j]
)?
0 <= grid[i][j] <= 50
.Here is a Java solution to compute the total surface area:
public class SurfaceArea3DShapes {
public int surfaceArea(int[][] grid) {
int n = grid.length;
int totalSurfaceArea = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] > 0) {
// Add surface area of the stack itself
totalSurfaceArea += 2 + grid[i][j] * 4;
// Subtract surfaces where adjacent cubes touch
if (i > 0) {
totalSurfaceArea -= Math.min(grid[i][j], grid[i - 1][j]) * 2;
}
if (j > 0) {
totalSurfaceArea -= Math.min(grid[i][j], grid[i][j - 1]) * 2;
}
}
}
}
return totalSurfaceArea;
}
public static void main(String[] args) {
SurfaceArea3DShapes sa = new SurfaceArea3DShapes();
int[][] grid = {
{2, 2, 2},
{2, 1, 2},
{2, 2, 2}
};
System.out.println(sa.surfaceArea(grid)); // Expected surface area
}
}
2 + grid[i][j] * 4
(since each cube contributes 4 side faces and the top and bottom faces add 2 more).grid[i-1][j]
), subtract the touching surface area.grid[i][j-1]
), subtract the touching surface area.O(n^2)
where n
is the side length of the grid. This is because we are iterating through every cell in an n x n
grid exactly once.O(1)
as we are using a constant amount of additional space.This approach ensures that you efficiently compute the surface area considering all edge cases and constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?