Reza Safari Blog
Published on

Shape Area - Unveiling the Polygon Area Calculation Challenge

Explanation:

Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3-, and 4-interesting polygons in the picture below.

Example:

For n = 2, the output should be

shapeArea(n) = 5;

For n = 3, the output should be

shapeArea(n) = 13;

In summary, the task provides a number, for example, 4. You need to move upwards, left, right, and downward according to the pattern shown in the picture. In each movement, the shape of this polygon with several sides should be preserved, as shown in the image.

This question is part of the initial challenges in CodeSignal, and I think I solved it about three years ago.

Well, back then, what came to my mind immediately was the solution below:

function shapeArea(n) {
  const middleCount = n * 2 - 1;
  let lastRes = middleCount;
  const rows = n - 1;
  let rowsSum = 0;

  for (let i = 0; i < rows; i++) {
    let sumRow = lastRes - 2;
    lastRes = sumRow;
    rowsSum += sumRow;
  }

  return rowsSum * 2 + middleCount;
}

Actually, I first found the number of cells in the middle row, which can be calculated as n * 2 - 1 (the number of cells in the middle row is always constant).

Then, I obtained the number of rows above the middle row, which is n - 1. Well, how can we calculate the colored cells on one side?

For example, if there are 3 rows above, it will be 3 * 3, which is 9. So, the number of colored cells above the middle row is 9.

Well, it's simple. The answer will be the number of colored cells above * 2, plus the middle row, which results in the following final formula:

function shapeArea(n) {
  const maximumColumns = n * 2 - 1;
  const rows = n - 1;
  const topRows = rows * rows;

  return maximumColumns + topRows * 2;
}

Tonight:

As I was browsing CodeSignal challenges again, I came across this problem and remembered it.

I thought to myself, let's think about it again and see if there is a simpler solution or not.

After about 20 minutes of thinking, I arrived at this formula:

n * n + (n - 1) * (n - 1);

In fact, it's the same formula as above, just shorter and more concise.

Do you have a shorter solution? I'd be delighted to know your solution as well.