
Problem
Solution
Submissions
Difference Between Two Matrices
Certification: Basic Level
Accuracy: 50%
Submissions: 6
Points: 10
Write a C++ program to find the difference between two matrices. The program should take two matrices of the same size as input and return their difference (A - B).
Example 1
- Input:
Matrix A = [
[1, 2],
[3, 4] ]
Matrix B = [
[5, 6],
[7, 8] ] - Output: [ [-4, -4], [-4, -4] ]
- Explanation:
- Step 1: Verify that matrices A and B have the same dimensions (2×2).
- Step 2: Create a result matrix with the same dimensions.
- Step 3: Subtract corresponding elements: result[0][0] = A[0][0] - B[0][0] = 1 - 5 = -4.
- Step 4: Continue for all elements: result[0][1] = 2 - 6 = -4, result[1][0] = 3 - 7 = -4, result[1][1] = 4 - 8 = -4.
- Step 5: Return the resulting matrix.
Example 2
- Input:
Matrix A = [
[1, 2, 3],
[4, 5, 6] ]
Matrix B = [
[7, 8, 9],
[10, 11, 12] ] - Output: [ [-6, -6, -6], [-6, -6, -6] ]
- Explanation:
- Step 1: Verify that matrices A and B have the same dimensions (2×3).
- Step 2: Create a result matrix with the same dimensions.
- Step 3: Subtract corresponding elements for each position in the matrices.
- Step 4: For the first row: [1-7, 2-8, 3-9] = [-6, -6, -6].
- Step 5: For the second row: [4-10, 5-11, 6-12] = [-6, -6, -6].
- Step 6: Return the resulting matrix.
Constraints
- The matrices must be of the same size
- The matrices can have a maximum size of 100×100
- Time Complexity: O(n²), where n is the size of the matrices
- Space Complexity: O(n²) for storing the result matrix
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use nested loops to iterate through the matrices and subtract corresponding elements.
- Store the result in a new matrix.