Matrix Diagonal Difference using Kotlin

Problem Description:

Given a square matrix, calculate the absolute difference between the sums of its diagonals:

  1. Primary Diagonal: Runs from the top-left corner to the bottom-right corner.
  2. Secondary Diagonal: Runs from the top-right corner to the bottom-left corner.

Mathematical Expression: If matrix[i][j] represents the element at the i-th row and j-th column:

  • Primary diagonal elements: matrix[i][i] where i=0,1,2,…,n−1
  • Secondary diagonal elements: matrix[i][n−i−1] where i=0,1,2,…,n−1

Goal: Compute:

Diagonal Difference = | Sum of Primary Diagonal−Sum of Secondary Diagonal |


Example

Input:

1124
456
108-12

Calculations:

  • Primary Diagonal: 11+5+(−12) = 4
  • Secondary Diagonal: 4+5+10=19
  • Absolute Difference: ∣4−19∣ = 15

Output: 15

Kotlin Solution

Below is a Kotlin implementation to calculate the diagonal difference:

Kotlin
fun diagonalDifference(matrix: Array<Array<Int>>): Int {
    val n = matrix.size
    var primaryDiagonalSum = 0
    var secondaryDiagonalSum = 0

    for (i in 0 until n) {
        primaryDiagonalSum += matrix[i][i]             // Add primary diagonal element
        secondaryDiagonalSum += matrix[i][n - i - 1]  // Add secondary diagonal element
    }

    return kotlin.math.abs(primaryDiagonalSum - secondaryDiagonalSum)
}

fun main() {
    // Example matrix
    val matrix = arrayOf(
        arrayOf(11, 2, 4),
        arrayOf(4, 5, 6),
        arrayOf(10, 8, -12)
    )

    val result = diagonalDifference(matrix)
    println("Diagonal Difference: $result") // Output: 15
}

Explanation of the Code

  1. Input Matrix:
    • The matrix is represented as a 2D array of integers.
  2. Diagonal Sums:
    • A for loop iterates through each row of the matrix (0 to n-1).
    • Add the element at [i][i] for the primary diagonal.
    • Add the element at [i][n-i-1] for the secondary diagonal.
  3. Absolute Difference:
    • The absolute difference is computed using kotlin.math.abs().
  4. Main Function:
    • An example matrix is tested to demonstrate the implementation.

Complexity Analysis

  • Time Complexity: O(n)O(n)O(n), where nnn is the number of rows/columns in the square matrix. The algorithm makes a single pass through the rows.
  • Space Complexity: O(1)O(1)O(1), as only a few variables are used to store intermediate sums.

This approach efficiently calculates the diagonal difference for any square matrix.

Leave a Comment