LeetCode Entry

1572. Matrix Diagonal Sum

8.05.2023 easy 2023 kotlin

avoid double counting of the center element

1572. Matrix Diagonal Sum easy


fun diagonalSum(mat: Array<IntArray>): Int =
    (0..mat.lastIndex).sumBy {
        mat[it][it] + mat[it][mat.lastIndex - it]
    }!! - if (mat.size % 2 == 0) 0 else mat[mat.size / 2][mat.size / 2]

blog post substack

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/206

Intuition

Just do what is asked.

Approach

  • avoid double counting of the center element

    Complexity

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)