Advanced Algorithms: Stacks of Cubes Surface Areaby@bab3nk0v
10,315 reads
10,315 reads

Advanced Algorithms: Stacks of Cubes Surface Area

by Aleksei BabenkovJanuary 12th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Tackling the classic algorithmic challenge of calculating a cube grid's 3D surface area, this article delves into a problem common in FAANG interviews. Starting with a specific example, it demonstrates the importance of analyzing individual cases before deriving a general formula. The solution involves a step-by-step matrix approach to determine visible surfaces, considering each cube's height and its neighbors. The method not only illustrates the problem-solving process in software development but also reinforces key concepts in computational geometry and logical thinking
featured image - Advanced Algorithms: Stacks of Cubes Surface Area
Aleksei Babenkov HackerNoon profile picture

In the algorithmic world, challenges such as calculating the 3D surface area of a cube grid are not only intellectually stimulating but also hone problem-solving and logical thinking skills essential in modern software development. This problem, sourced from the HackerRank website, is a classic algorithmic challenge frequently encountered in coding interviews, particularly with tech giants like FAANG.

The Problem: A Grid of Cubes

Imagine a grid where each cell may contain a stack of cubes with varying heights, much like a miniature cityscape with buildings of different sizes. Our task is to calculate the total visible surface area of these stacked cubes. This challenge is akin to estimating the visible exterior of a cityscape composed of buildings of different heights.


1 3 4
2 2 3 -> 60
1 2 4

Understanding Cube Arrangement and Surface Visibility

Each cube in our grid can be seen as a skyscraper within the city

Each cube in our grid is akin to a small building within a city. The challenge lies in figuring out which parts of these buildings are visible from an external viewpoint.

  • Top and Bottom Surfaces: No matter how high a cube is, its top and bottom surfaces are always visible unless obscured by another cube directly on top.
  • Side Surfaces: The visibility of a cube's sides depends on its height relative to adjacent cubes. If a cube is taller than its neighbor, the portion exceeding the neighbor's height is visible. If it's the same height or shorter, the side is obscured.

To assess the side visibility more accurately, we examine each cube in relation to its immediate neighbors:

  1. Fully Visible Side: If there’s no adjacent cube on a side, that entire side is visible.
  2. Partially Visible Side: When the cube’s neighbor is shorter, the difference in height is the visible portion.
  3. No Visibility: If the neighbor is as tall or taller, the side of the cube is not visible.

This analysis involves careful consideration of each cube's position and its relationship with surrounding cubes, allowing us to accurately sum up all the visible areas.

This leads to the idea of a solution: each cell of the grid visits its 4 neighbors, summing all the differences in heights.

To illustrate this concept, let's dive into the example provided and break down the surface area calculation step by step:

1 3 4
2 2 3
1 2 4

Initially, we create a new matrix mirroring the dimensions of our grid. This matrix will progressively be filled with the calculated surface area of each individual cube. For each cube, if its height is greater than zero, it contributes two units to the area (for the top and bottom surfaces). We add these to our surface area matrix.

2 2 2 
2 2 2 
2 2 2

Calculate Side Surfaces: Now, we examine each cube's sides. The side is visible if the cube is taller than its neighboring cube. The visible area is the difference in their heights. We do this for each cube by comparing it with its neighbors (left, right, top, and bottom).

For example, for the cube at (1,2) with height 3:

1 3 4
2 2 3 <- this one
1 2 4
  1. Left neighbour (1,1) has height 2. Visible side area = 3 - 2 = 1.
  2. Right neighbour (1,3) is out of bounds, assume height 0. 3 - 0 = 3
  3. Top neighbour (0,2) has height 4. No visible side area(=0) since 3 - 4 is negative.
  4. Bottom neighbour (2,2) has height 4. No visible side area(=0) since 3 - 4 is negative.

So, the total surface area of this stack of cubes will be:

2(already written in the matrix) + 1(left) + 3(right) + 0 + 0 = 6.

So, let’s update our value:

2 2 2 
2 2 6 <- here it is 
2 2 2

We perform similar calculations for each cube and update our matrix.

Summing It All Up: Once we calculate the areas for all the cubes, we sum up the values in our surface area matrix. This total gives us the total visible surface area for the entire grid of cubes.

After performing these steps, we end up with a matrix that represents the surface area of each cube, and by summing all these values, we get the total visible surface area for the grid.

4 8 12
6 2 6
4 5 13

After summing this area matrix we get 60 as a final answer. This methodical approach helps in visualizing and understanding the problem, making it easier to implement in a programming context.

Mathematical formulation

Now, let's delve deeper into the formula itself and dissect its components:

  • S: Represents the total surface area we want to calculate.
  • : This symbol denotes summation. It means we sum the following expression for each cube in the grid.
  • i, j: These are indices representing the position of each cube in the grid.
  • 2: Accounts for the top and bottom surfaces of each cube. Since these surfaces are always visible for each cube, we count two units of area for every cube.
  • ∑ (di, dj) ∈ neighbors: This summation iterates over each neighbor of the cube. The neighbors are the adjacent cubes in the grid. The terms "di" and "dj" represent the relative position of these neighboring cubes to the current cube located at (i, j).
  • neighbors: This variable represents a list of pairs, where each pair (di,dj) defines the relative positions of neighboring cubes concerning the current cube at (i,j). For example, (0,1) signifies a neighboring cube that is positioned to the right of the current cube, and (1,0) represents a neighboring cube located just below the current cube. The list continues to enumerate all adjacent positions, covering the top, bottom, left, and right directions, ensuring a comprehensive assessment of neighboring cubes for each cube in the grid.
  • A[i][j]: This is the height of the cube at position (i, j). It represents how many cubes are stacked at this particular grid position.
  • A[i+di][j+dj]: The height of the cube at a neighboring position. This is the height of the stack of cubes in one of the adjacent cells to the cell at (i, j).
  • max(A[i][j] - A[i+di][j+dj], 0): This part of the formula calculates the visible side area for each pair of adjacent cubes. We subtract the height of the neighbor (A[i+di][j+dj]) from the height of the current cube (A[i][j]). If the result is positive, it means that part of the side of the current cube is visible. We use the max function to ensure that we don't count negative values, which would imply that the side is not visible because the neighboring cube is taller.


An example implementation that, in fact, just implements our derived formula in Python can be found below. It also sums the whole area directly into the resulting variable, not in the intermediate matrix, since we need only the total area.

  (0, 1),
  (1, 0),
  (-1, 0),
  (0, -1)

# helper function
def height(A, i, j):
    n = len(A)
    m = len(A[0])
    if 0 <= i < n and 0 <= j < m:
        return A[i][j]
    return 0

def surfaceArea(A):
    n = len(A)
    m = len(A[0])
    area = 0
    for i in range(n):
        for j in range(m):  # outer sum by all the grid
            if height(A, i, j) > 0:
                area += 2
            for (di, dj) in NEIGHBOURS:  # inner sum by neighbours 
                neighbour_h = height(A, i + di, j + dj)
                diff_height = height(A, i, j) - neighbour_h
                area += max(diff_height, 0)
    return area

Similar real-world problems and areas

  • Computational Geometry and 3D Visualization: Similar to calculating visible cube surfaces, these fields use algorithms to render complex shapes and determine visible areas.
  • Computer Graphics and Virtual Reality: Algorithms assess the visibility of complex forms, akin to the cube surface problem, crucial for realistic visualizations in games and VR.
  • Pathfinding in AI and Game Design: Algorithms like A* and Dijkstra's evaluate efficient routes, paralleling the concept of visibility in the cube problem.
  • GIS Computational Geometry: Used for visibility analyses such as sightlines and horizon views, echoing the cube surface calculation logic.

Enjoyed this deep dive into algorithmic problem-solving? Stay tuned for more intriguing content!