#892
Surface Area of 3D Shapes
EasyArrayMathGeometryMatrixArrayMatrix
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
The optimal solution leverages the same principles as the brute-force approach but minimizes redundant calculations by directly calculating the contributions from each cube's height and its neighbors, reducing unnecessary checks.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable 'surface_area' to 0.
- 2Step 2: Loop through each cell in the grid. For each cell, calculate the total surface area contribution.
- 3Step 3: For each cube, add 4 times its height plus 2 for the top and bottom.
- 4Step 4: Subtract the contributions from adjacent cells only if they exist.
- 5Step 5: Return the total surface area.
solution.py16 lines
1def surfaceArea(grid):
2 n = len(grid)
3 surface_area = 0
4 for i in range(n):
5 for j in range(n):
6 if grid[i][j] > 0:
7 surface_area += 4 * grid[i][j] + 2
8 if i > 0:
9 surface_area -= min(grid[i][j], grid[i-1][j])
10 if j > 0:
11 surface_area -= min(grid[i][j], grid[i][j-1])
12 if i < n - 1:
13 surface_area -= min(grid[i][j], grid[i+1][j])
14 if j < n - 1:
15 surface_area -= min(grid[i][j], grid[i][j+1])
16 return surface_areaℹ
Complexity note: The time complexity remains O(n²) since we still iterate through each cell in the grid. The space complexity is O(1) as we only use a few variables to store the surface area.
- 1Each cube contributes to its own surface area, but adjacent cubes share surfaces that need to be subtracted.
- 2The bottom face of each cube is always counted, regardless of its position.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.