Forming a Magic Square in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of HackerRank, Algorithm Solutions of Problem Solving Section in Java. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Forming a Magic Square in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Introduction To Algorithm

The word Algorithm means “a process or set of rules to be followed in calculations or other problem-solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results. 

Advantages of Algorithms:

  • It is easy to understand.
  • Algorithm is a step-wise representation of a solution to a given problem.
  • In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program.

Link for the ProblemForming a Magic Square – Hacker Rank Solution

Forming a Magic Square – Hacker Rank Solution


We define a magic square to be an  matrix of distinct positive integers from  to  where the sum of any row, column, or diagonal of length  is always equal to the same number: the magic constant.

You will be given a  matrix  of integers in the inclusive range . We can convert any digit  to any other digit  in the range  at cost of . Given , convert it into a magic square at minimal cost. Print this cost on a new line.

Note: The resulting magic square must contain distinct integers in the inclusive range .


$s = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]

The matrix looks like this:

5 3 4
1 5 8
6 4 2

We can convert it to the following magic square:

8 3 4
1 5 9
6 7 2

This took three replacements at a cost of .

Function Description

Complete the formingMagicSquare function in the editor below.

formingMagicSquare has the following parameter(s):

  • int s[3][3]: a  array of integers


  • int: the minimal total cost of converting the input square to a magic square

Input Format

Each of the  lines contains three space-separated integers of row .


Sample Input 0

4 9 2
3 5 7
8 1 5

Sample Output 0


Explanation 0

If we change the bottom right value, , from  to  at a cost of ,  becomes a magic square at the minimum possible cost.

Sample Input 1

4 8 2
4 5 7
6 1 6

Sample Output 1


Explanation 1

image 69
Forming a Magic Square – Hacker Rank Solution
import java.util.Scanner;

 * @author Techno-RJ
public class FormingAMagicSquare {
	 static int formingMagicSquare(int[][] s) {
	       int[][][] magicSquareCombinations={ {{4,9,2},{3,5,7},{8,1,6}},
		int minCost = Integer.MAX_VALUE;
		for (int i = 0; i < magicSquareCombinations.length; i++) {
			int modifyCost = 0;
			for (int j = 0; j < 3; j++) {
				for (int k = 0; k < 3; k++) {
					modifyCost += Math.abs(s[j][k] - magicSquareCombinations[i][j][k]);
			minCost = Math.min(modifyCost, minCost);
		return minCost;
	    public static void main(String[] args) {
	        Scanner in = new Scanner(;
	        int[][] s = new int[3][3];
	        for(int s_i = 0; s_i < 3; s_i++){
	            for(int s_j = 0; s_j < 3; s_j++){
	                s[s_i][s_j] = in.nextInt();
	        int result = formingMagicSquare(s);

32 thoughts on “Forming a Magic Square in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]”

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock