Magic Square HackerRank Exercise

Photo by Blake Connally on Unsplash


Defined a magic square n x n to be a matrix of distinct positive integers from 1 to n² where the sum of any row, column, or diagonal of length n is always equal to the same number: the magic constant. The given 3 x 3 a matrix s of integers in the inclusive range [1, 9]. The program can convert any digit a to any other digit b in the range [1, 9] at cost of [a — b]. Given s, convert it into a magic square at a minimal cost. Print this cost on a new line.


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 3 x 3 should contain only n ^ 2 = 1, 2, 3, 4, 5, 6, 7, 8, 9
  • The order has matter!

So, in this exercise, we have only a 3 x 3 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 n x n matrix. 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 3 x 3 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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Dynamic Channels for Video Chat Using Agora RTM on React Native

Thumbnails in Warclight

The Top Technical Screening Platforms in 2019

SQL challenge

I Need your Help Developing Life Changing Software on the Blockchain

Learn Terraform by deploying a Google Kubernetes Engine cluster

Calico Networking with eBPF on GCP — CNCF Roadmap

Newsletter of Carlos Santana — Issue #17

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Almost Engineer

Almost Engineer

iOS Software Developer

More from Medium

How to Create A Basic API Call in SwiftUI ?

Cisco IOS Ultimate Guide

5 Best iOS Design Patterns in Swift to Develop Powerful iPhone Apps

RxSwift: Combining Operators in Practice