Shape Area DS & Algorithm Problem Solution Walkthrough

Fabrice Innocent
Strategio
Published in
2 min readSep 8, 2022

Data structures and algorithms are a part of the interview process for many organizations. As a career changer and bootcamp grad I had no idea how to approach these kinds of problems and they always felt overwhelming. If that’s how you’ve also felt, I’d like to ease you into an example problem to get your feet wet on your data structure and algorithms problem solving journey. Here is an example problem 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
    solution(n) = 5;
  • For n = 3, the output should be
    solution(n) = 13.

First, looking at the graph we need to visualize it from another angle. If we look at the graph diagonally it becomes apparent that N is equal to the sides of the square. For example, if n = 5 then the square will have five squares on each side which equates to N * N.

Secondly, looking at the graph we can see that the result of N *N does not factor in all the squares in the graph. There are squares in between the sides of the square that are unaccounted for. To find the amount of the unaccounted for squares we would subtract 1 from n. Now our formula is N * N + (n-1) * (n-1).

Lastly to complete the problem we would have 5 * 5 = 25 being the total of the squares on the side of the polygon. (5–1) * (5–1) is how we would calculate the inner squares of the polygon which would equal 16. Therefore, in total we would have 41 squares.

In conclusion, I recommend utilizing different resources and even courses that will give you insight into how to mentally approach these problems. There many YouTube channels devoted to helping others develop more efficiency in that area. Best of luck!

--

--