-
Notifications
You must be signed in to change notification settings - Fork 254
Diagonal
Raymond Chen edited this page Aug 1, 2024
·
4 revisions
"TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Matrices, Diagonals
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- The function
diagonal_sum()
should take a 2D n x n matrix grid and return the sum of the primary and secondary diagonals. The center element should be counted only once if it is part of both diagonals.
HAPPY CASE
Input: [ [1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Expected Output: 25
Input: [ [1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
]
Expected Output: 8
EDGE CASE
Input: [ [5]
]
Expected Output: 5
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the matrix to sum the elements on the primary diagonal and the secondary diagonal, avoiding double counting the center element if n is odd.
1. Initialize `total_sum` to 0.
2. Get the size of the matrix `n`.
3. Iterate through the matrix with index `i` from 0 to `n-1`.
- Add `grid[i][i]` to `total_sum` (primary diagonal).
- If `i` is not the center element, add `grid[i][n-1-i]` to `total_sum` (secondary diagonal).
4. Return `total_sum`
- Double counting the center element if n is odd.
- Misindexing elements on the secondary diagonal.
Implement the code to solve the algorithm.
def diagonal_sum(grid):
n = len(grid)
total_sum = 0
for i in range(n):
total_sum += grid[i][i] # Primary diagonal
if i != n - 1 - i: # Check to avoid double counting the center element
total_sum += grid[i][n - 1 - i] # Secondary diagonal
return total_sum