Matrix Addition - codepath/compsci_guides GitHub Wiki
TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, Matrix Manipulation
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What is the input to the function?
- A: The input consists of two
n x m
matricesmatrix1
andmatrix2
.
- A: The input consists of two
-
Q: What is the expected output of the function?
- A: The function should return an
n x m
matrixsum_matrix
, where each element is the sum of the corresponding elements frommatrix1
andmatrix2
.
- A: The function should return an
-
Q: What should the function return if the matrices are empty?
- A: If the input matrices are empty, the function should return an empty matrix.
-
Q: Are the matrices guaranteed to have the same dimensions?
- A: Yes, the problem assumes that both matrices have the same dimensions.
-
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](/codepath/compsci_guides/wiki/1)
matrix2 = [1](/codepath/compsci_guides/wiki/1)
Expected Output: [2](/codepath/compsci_guides/wiki/2)
P-lan
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
⚠️ Common Mistakes
- Forgetting to ensure both matrices are of the same size.
- Not properly initializing the sum matrix.
I-mplement
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