Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

892. Surface Area of 3D Shapes

Explanation

To solve this problem, we can iterate through each cell in the grid and calculate the contribution of each cell to the total surface area. The surface area of a single cube is 6, and we need to consider the surface area of each cell as well as the shared faces with adjacent cells. We will calculate the total surface area by subtracting the areas of the shared faces.

  1. Iterate through each cell in the grid.
  2. For each cell, calculate the surface area contributed by that cell (4 sides * height) and add it to the total surface area.
  3. For each cell, check its adjacent cells to subtract the shared faces. If the adjacent cell has a higher value, subtract the overlapping faces. If the adjacent cell has a lower value, do not subtract anything (as the face is already accounted for in the adjacent cell's calculation).
  4. Return the total surface area.

The time complexity of this solution is O(n^2) as we are iterating through each cell in the grid. The space complexity is O(1) as we are using only a constant amount of extra space.

class Solution {
    public int surfaceArea(int[][] grid) {
        int n = grid.length;
        int surfaceArea = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] > 0) {
                    surfaceArea += 4 * grid[i][j] + 2;
                    if (i > 0) {
                        surfaceArea -= 2 * Math.min(grid[i][j], grid[i - 1][j]);
                    }
                    if (j > 0) {
                        surfaceArea -= 2 * Math.min(grid[i][j], grid[i][j - 1]);
                    }
                }
            }
        }

        return surfaceArea;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.