Clearwater Analytics

Interview Question

Software Engineer Interview(Student Candidate) Boise, ID

Given a cube made up of n x n x n smaller cubes, write a

  function that finds the number of smaller cubes with at least one face showing.

Interview Answer

1 Answer


If you play with Rubik's cubes like I do, this one should be too hard to figure out. Just consider the cube in layers and then figure out the equations with a given n (like 12).

First, you have the top and bottom layer. Each of those have n x n smaller cubes with at least one face showing (2 * n * n).

Then, you have n-2 layers in between the top and bottom (10 layers for n = 12). Each of those layers has 4 corner cubes and n-2 cubes in between the corners on each face (n-2) * (4 + 4*(n-2)).

Be sure you account for the edge cases where n = 1 or n <= 0. Here is my solution:

int func1(int n)
    if (n == 1)
        return 1;
    else if (n <= 0)
        return -1; //or throw an exception
    int total = 0;
    total += 2 * n * n;
    int layers = 2 - n;
    total += layers * (4 + 4*(n-2));
    return total;

Interview Candidate on Oct 27, 2011

Add Answers or Comments

To comment on this, Sign In or Sign Up.