Given two matrices A and B with the same number of rows and columns, add both matrices and return the resulting matrix.
Matrix addition works cell by cell. Each cell in the result matrix stores the sum of the corresponding cell from A and the corresponding cell from B.
Example 1
Input: A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
Output: [[6, 8], [10, 12]]
Explanation: Corresponding cells are added: 1 + 5 = 6, 2 + 6 = 8, 3 + 7 = 10, and 4 + 8 = 12.
Example 2
Input: A = [[10, -2, 3], [4, 0, 6]], B = [[1, 2, 3], [-4, 5, 6]]
Output: [[11, 0, 6], [0, 5, 12]]
Explanation: Each result cell stores the sum of matching positions from both matrices.
Approach
Matrix addition is performed by adding corresponding elements from both matrices. Since each element in the result depends only on the values at the same row and column, we simply traverse both matrices together and store the sum in a new result matrix.
Algorithm
Create a result matrix with the same dimensions as the input matrices.
Traverse every row using an outer loop.
For each row, traverse all columns using an inner loop.
Add the corresponding elements from both matrices and store the sum in the result matrix.
Return the result matrix after all elements have been processed.
Dry Run
add two matrix
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Function to add two matrices. vector<vector<int>> addMatrices(vector<vector<int>>& A, vector<vector<int>>& B) { // Store total number of rows. int n = A.size(); // Handle empty matrices. if (n == 0) { return {}; } // Store total number of columns. int m = A[0].size(); // Create a result matrix with the same dimensions. vector<vector<int>> result(n, vector<int>(m, 0)); // Traverse every row from top to bottom. for (int row = 0; row < n; row++) { // Traverse every column from left to right. for (int col = 0; col < m; col++) { // Store the sum of corresponding cells. result[row][col] = A[row][col] + B[row][col]; } } // Return the final matrix sum. return result; }};// Function to print a matrix.void printMatrix(vector<vector<int>>& mat) { // Traverse every row for printing. for (int row = 0; row < (int)mat.size(); row++) { // Traverse every column for printing. for (int col = 0; col < (int)mat[row].size(); col++) { if (col > 0) { cout << " "; } cout << mat[row][col]; } cout << "\n"; }}// Driver code.int main() { vector<vector<int>> A = {{1, 2}, {3, 4}}; vector<vector<int>> B = {{5, 6}, {7, 8}}; Solution sol; vector<vector<int>> result = sol.addMatrices(A, B); printMatrix(result); return 0;}Complexity Analysis
Time Complexity: O(N × M), traversal visits every matrix cell exactly once.
Space Complexity: O(N × M), result matrix stores the sum of both matrices.
Interview follow-up Questions
No. Matrix addition needs the same number of rows and columns in both matrices.
Be the first to add a comment.