Compute the Z Sum of a Matrix


Given an n by n integer matrix, return the sum of all elements that form a Z in the matrix.

Constraints
n ≤ 1,000
Example 1
Input

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

Output
35
Explanation
The Z that’s formed is [1, 2, 3, 5, 7, 8, 9] and its sum is 35.

Matrix Z Sum Algorithm

The fastest way to compute the Z sum should be consist of three parts: the sum of first row, the sum of last row, and the sum of the diagonal (but should not double counting the two corners). In Python, we can use the sum function to obtain the sum of the first, and the last row easily. We then need to loop along the diagonal.

1
2
3
4
5
6
7
8
class Solution:
    def zSumOfMatrix(self, matrix):
        first = sum(matrix[0])
        last = sum(matrix[-1])
        ans = first + last
        for i in range(1, len(matrix) - 1):
            ans += matrix[i][len(matrix) - i - 1]
        return ans
class Solution:
    def zSumOfMatrix(self, matrix):
        first = sum(matrix[0])
        last = sum(matrix[-1])
        ans = first + last
        for i in range(1, len(matrix) - 1):
            ans += matrix[i][len(matrix) - i - 1]
        return ans

The space complexity is O(1). The time complexity is O(N) where N is the dimension of the matrix.

–EOF (The Ultimate Computing & Technology Blog)

GD Star Rating
loading...
256 words
Last Post: Teaching Kids Programming - Compute the Intersection of the Intervals
Next Post: Recursive Algorithm to Convert a List to Binary Search Tree

The Permanent URL is: Compute the Z Sum of a Matrix

Leave a Reply