Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hackerrank Diagonal Difference Question in JavaScript

I am trying to complete the Diagonal Difference Question of Hackerrank with the following JavaScript code,

function diagonalDifference(arr) {
// Write your code here
let right = 0;
let left = 0;
const row = Math.sqrt(arr.length);
for (let i=0; i<arr.length; i=i+row){
        right+= arr[i]
        i++
}
for (let i=row; i<arr.length; i=i+row){
        left+= arr[i-1]
        i--
}

let res = Math.abs(right-left)
return res

}

However, the answer keeps coming out as wrong answer
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Besides, I tried running this code in other IDE’s and everything else gives me the correct output

>Solution :

You are almost there, try using one loop instead

const arr = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

const diagonalDifference = (arr) => {
  const length = arr.length;
  let left = 0,
    right = 0;

  for (let i = 0; i < length; i++) {
    left += arr[i][i];
    right += arr[length - 1 - i][i]
  }

  console.log(Math.abs(left - right));

  return Math.abs(left - right);
}

diagonalDifference(arr)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading