LeetCode 892: Surface Area of 3D Shapes Solution

Master LeetCode problem 892 (Surface Area of 3D Shapes), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

892. Surface Area of 3D Shapes

Problem Explanation

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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 892 (Surface Area of 3D Shapes)?

This page provides optimized solutions for LeetCode problem 892 (Surface Area of 3D Shapes) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 892 (Surface Area of 3D Shapes)?

The time complexity for LeetCode 892 (Surface Area of 3D Shapes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 892 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 892 in Java, C++, or Python.

Back to LeetCode Solutions