Magic Square HackerRank Exercise

Photo by Blake Connally on Unsplash



The solving of this exercise isn’t so difficult. The main issue here is to understand the meaning and specification. I want to define the main parts of the magic square:

  • All rows, columns, diagonals are always equal to , where n is a matrix size. (Matrix should be a square)
  • Items should be the arithmetic progression. Matrix with all number 3 or 4 for example is not a magic square. (It can be helpful if you need to calculate the sum of all items in a huge magic square). So the magic square should contain only
  • The order has matter!

So, in this exercise, we have only a matrix. Magic square like that has only 8 possible variations of order. We need to compare this matrix with all these variations. The solving can be smarter for . But it was so slow (exercises on HackerRank has time complexity limitations, and that’s why solving looks silly).

We need to create all possible variations of the magic square with size. Then calculate the difference between each variation and input matrix. The minimum value of these differences is our answer

My Social Media

LinkedIn Twitter Original Blog Github HackerRank

iOS Software Developer