49. Cross Diagonal Weight

A tile floor is laid out as a square grid and the weight of every tile is stored in grid, which has n rows and n columns. A cross-shaped brace runs along both diagonals of the floor: from the top-left corner to the bottom-right corner, and from the top-right corner to the bottom-left corner.

Return the total weight of all tiles that lie on at least one of the two diagonals. When n is odd the two diagonals meet at the centre tile, which must be counted only once.

You only need to visit one tile per row from each diagonal, so the work should be proportional to n, not n * n.

Example 1

Input:
grid = [[2,4,6],[8,10,12],[14,16,18]]
Output:
50
Explanation:

The diagonals hold 2, 10, 18 and 6, 10, 14; the centre 10 counts once, so the total is 50.

Example 2

Input:
grid = [[1,1],[1,1]]
Output:
4
Explanation:

In a 2 by 2 grid every tile is on a diagonal, so the total is 4.

Constraints

1 ≤ n ≤ 100

1 ≤ grid[i][j] ≤ 100

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…