Looking for help to determine the time complexity of this code snippet!
Context: I came across this algorithm problem on HackerRank where the solution provided in the editorial section claims a time complexity of O(n^2), but I personally think it's actually O(n).
I argue that the time complexity is O(n) because we only iterate through the 2D array once with a single loop, avoiding nested loops and reducing the number of iterations.
Question:
Is my assumption correct or am I overlooking something?
Solution:
//arr represents a 2D array with equal rows and columns
function diagonalDifference(arr) {
let diff = 0;
const length = arr.length - 1;
for (let i = 0; i < arr.length; i++) {
diff += arr[i][i] - arr[i][length - i];
}
return Math.abs(diff);
}
Challenge:
Given a square matrix (or 2D Array), find the absolute difference between the sums of its diagonals.
For example, consider the square matrix arr:
1 2 3 4 5 6 9 8 9
The sum of left-to-right diagonal = 1 + 5 + 9 = 15. The sum of right-to-left diagonal = 3 + 5 + 9 = 17. The absolute difference between them is |15 - 17| = 2.