-
Notifications
You must be signed in to change notification settings - Fork 259
Matrix Addition
Raymond Chen edited this page Aug 2, 2024
·
4 revisions
TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, Matrix Manipulation
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 add_matrices() should take two matrices of the same dimensions and return a new matrix where each element is the sum of the corresponding elements in the two input matrices.
HAPPY CASE
Input:
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
Expected Output:
[[10, 10, 10],
[10, 10, 10],
[10, 10, 10]]
EDGE CASE
Input:
matrix1 = [[1]]
matrix2 = [[1]]
Expected Output: [[2]]
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through both matrices and sum the corresponding elements to create a new matrix.
1. Get the dimensions of the matrices (rows and columns).
2. Initialize a new sum matrix with the same dimensions, filled with zeros.
3. Loop through each row and column:
a. Sum the corresponding elements from matrix1 and matrix2.
b. Store the result in the sum matrix.
4. Return the sum matrix
- Forgetting to ensure both matrices are of the same size.
- Not properly initializing the sum matrix.
Implement the code to solve the algorithm.
def add_matrices(matrix1, matrix2):
# Get the dimensions of the matrices
rows = len(matrix1)
cols = len(matrix1[0])
# Initialize the sum matrix with zeros
sum_matrix = []
for _ in range(rows):
sum_matrix.append([0] * cols)
# Iterate through each element and sum the corresponding elements
for i in range(rows):
for j in range(cols):
sum_matrix[i][j] = matrix1[i][j] + matrix2[i][j]
return sum_matrix