Matrix Problems in Data Structures and Algorithms
1. What Is a Matrix?
A matrix is a rectangular arrangement of elements organized into rows and columns. In programming, a matrix is commonly represented using a two-dimensional array.
If a matrix contains m rows and n columns, its dimensions are represented as m × n.
Example
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
The matrix looks like this:
1 2 3
4 5 6
7 8 9
This matrix contains 3 rows, 3 columns, and 9 elements.
2. Types of Matrices
Square Matrix
A square matrix has an equal number of rows and columns.
1 2
3 4
Rectangular Matrix
A rectangular matrix has a different number of rows and columns.
1 2 3
4 5 6
Row Matrix
A row matrix contains only one row.
1 2 3 4
Column Matrix
A column matrix contains only one column.
1
2
3
4
Diagonal Matrix
A diagonal matrix is a square matrix in which all non-diagonal elements are zero.
5 0 0
0 8 0
0 0 3
Identity Matrix
An identity matrix is a square matrix in which all diagonal elements are 1 and all other elements are 0.
1 0 0
0 1 0
0 0 1
3. Row-Wise and Column-Wise Traversal
Matrix traversal means visiting every element of a matrix. Nested loops are generally used for this operation.
Row-Wise Traversal
Row-wise traversal visits all elements of one row before moving to the next row.
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
1 2 3
4 5 6
7 8 9
Column-Wise Traversal
Column-wise traversal visits all elements of one column before moving to the next column.
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int j = 0; j < 3; j++) {
for (int i = 0; i < 3; i++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
1 4 7
2 5 8
3 6 9
4. Sum of Each Row and Column
We can calculate the sum of every row and every column by traversing the matrix and maintaining separate sum variables.
C++ Program
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Row sums
for (int i = 0; i < 3; i++) {
int sum = 0;
for (int j = 0; j < 3; j++) {
sum += matrix[i][j];
}
cout << "Row " << i
<< " Sum = " << sum << endl;
}
// Column sums
for (int j = 0; j < 3; j++) {
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += matrix[i][j];
}
cout << "Column " << j
<< " Sum = " << sum << endl;
}
return 0;
}
Output
Row 0 Sum = 6
Row 1 Sum = 15
Row 2 Sum = 24
Column 0 Sum = 12
Column 1 Sum = 15
Column 2 Sum = 18
Complexity Analysis
- Time Complexity: O(rows × columns) for calculating all row and column sums.
- Auxiliary Space Complexity: O(1).
5. Main Diagonal Sum
The main diagonal of a square matrix contains elements whose row and column indices are equal.
The condition for a main diagonal element is:
i == j
Example
1 2 3
4 5 6
7 8 9
The main diagonal elements are 1, 5, and 9.
Sum = 1 + 5 + 9 = 15.
C++ Program
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += matrix[i][i];
}
cout << "Main diagonal sum = " << sum;
return 0;
}
Output
Main diagonal sum = 15
Complexity Analysis
- Time Complexity: O(n).
- Auxiliary Space Complexity: O(1).
6. Secondary Diagonal Sum
The secondary diagonal runs from the top-right corner to the bottom-left corner of a square matrix.
For an n × n matrix, the secondary diagonal condition is:
i + j == n - 1
Example
1 2 3
4 5 6
7 8 9
The secondary diagonal elements are 3, 5, and 7.
Sum = 3 + 5 + 7 = 15.
C++ Program
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int n = 3;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += matrix[i][n - 1 - i];
}
cout << "Secondary diagonal sum = " << sum;
return 0;
}
Output
Secondary diagonal sum = 15
7. Matrix Addition
Matrix addition is performed by adding corresponding elements of two matrices. Both matrices must have the same dimensions.
The formula is:
C[i][j] = A[i][j] + B[i][j]
C++ Program
#include <iostream>
using namespace std;
int main() {
int A[2][2] = {
{1, 2},
{3, 4}
};
int B[2][2] = {
{5, 6},
{7, 8}
};
int C[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
cout << "Result:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
6 8
10 12
8. Matrix Multiplication
Matrix multiplication combines rows of the first matrix with columns of the second matrix.
If matrix A has dimensions m × n and matrix B has dimensions n × p, their product C has dimensions m × p.
The multiplication formula is:
C[i][j] += A[i][k] * B[k][j]
Example
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
First element of the result:
C[0][0] = (1 * 5) + (2 * 7)
= 5 + 14
= 19
Complete result:
19 22
43 50
C++ Program
#include <iostream>
using namespace std;
int main() {
int A[2][2] = {
{1, 2},
{3, 4}
};
int B[2][2] = {
{5, 6},
{7, 8}
};
int C[2][2] = {0};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
cout << "Product:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
Product:
19 22
43 50
Complexity Analysis
- Time Complexity: O(m × n × p), where A has dimensions m × n and B has dimensions n × p.
- Auxiliary Space Complexity: O(m × p) for storing the result matrix.
9. Search in a Matrix
Searching means finding whether a given target value exists in a matrix. A simple approach is to check every element one by one.
Linear Search in a Matrix
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
int target = 50;
bool found = false;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == target) {
found = true;
cout << "Found at position: "
<< i << ", " << j << endl;
break;
}
}
if (found) {
break;
}
}
if (!found) {
cout << "Element not found.";
}
return 0;
}
Output
Found at position: 1, 1
Complexity Analysis
- Time Complexity: O(rows × columns) in the worst case.
- Auxiliary Space Complexity: O(1).
10. Searching in a Row-Wise and Column-Wise Sorted Matrix
A more efficient search is possible when a matrix follows these rules:
- Every row is sorted in increasing order.
- Every column is sorted in increasing order.
We can start from the top-right corner of the matrix.
- If the current element equals the target, the search is complete.
- If the current element is greater than the target, move left.
- If the current element is smaller than the target, move down.
Example
10 20 30 40
15 25 35 45
27 29 37 48
32 33 39 50
Suppose the target is 29. Start from 40 at the top-right corner.
Since 40 is greater than 29, move left. Continue until 29 is found.
C++ Program
#include <iostream>
using namespace std;
int main() {
int matrix[4][4] = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}
};
int target = 29;
int i = 0;
int j = 3;
bool found = false;
while (i < 4 && j >= 0) {
if (matrix[i][j] == target) {
found = true;
cout << "Found at: " << i
<< ", " << j;
break;
}
else if (matrix[i][j] > target) {
j--;
}
else {
i++;
}
}
if (!found) {
cout << "Element not found.";
}
return 0;
}
Output
Found at: 2, 1
Complexity Analysis
- Time Complexity: O(rows + columns).
- Auxiliary Space Complexity: O(1).
11. Spiral Traversal of a Matrix
Spiral traversal means visiting matrix elements in a spiral pattern, usually starting from the top-left corner and moving right, down, left, and up.
Example
Given matrix:
1 2 3
4 5 6
7 8 9
Spiral traversal:
1 2 3 6 9 8 7 4 5
Approach
Maintain four boundaries:
- top: First unvisited row.
- bottom: Last unvisited row.
- left: First unvisited column.
- right: Last unvisited column.
Repeat these four movements:
- Traverse from left to right across the top row.
- Traverse from top to bottom along the right column.
- Traverse from right to left across the bottom row, if it remains.
- Traverse from bottom to top along the left column, if it remains.
C++ Program
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int top = 0;
int bottom = 2;
int left = 0;
int right = 2;
while (top <= bottom && left <= right) {
// Left to right
for (int i = left; i <= right; i++) {
cout << matrix[top][i] << " ";
}
top++;
// Top to bottom
for (int i = top; i <= bottom; i++) {
cout << matrix[i][right] << " ";
}
right--;
// Right to left
if (top <= bottom) {
for (int i = right; i >= left; i--) {
cout << matrix[bottom][i] << " ";
}
bottom--;
}
// Bottom to top
if (left <= right) {
for (int i = bottom; i >= top; i--) {
cout << matrix[i][left] << " ";
}
left++;
}
}
return 0;
}
Output
1 2 3 6 9 8 7 4 5
Complexity Analysis
- Time Complexity: O(rows × columns), because each element is visited exactly once.
- Auxiliary Space Complexity: O(1), excluding the input matrix.
12. Rotate a Matrix by 90 Degrees
Rotating a square matrix by 90 degrees clockwise means moving each element to a new position so that rows become columns in reversed order.
A common in-place approach for a square matrix is:
- Find the transpose of the matrix.
- Reverse every row of the transposed matrix.
Example
Original matrix:
1 2 3
4 5 6
7 8 9
After 90-degree clockwise rotation:
7 4 1
8 5 2
9 6 3
C++ Program
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int n = 3;
// Step 1: Transpose the matrix
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
// Step 2: Reverse every row
for (int i = 0; i < n; i++) {
reverse(matrix[i], matrix[i] + n);
}
cout << "Rotated matrix:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
Rotated matrix:
7 4 1
8 5 2
9 6 3
Complexity Analysis
- Time Complexity: O(n²).
- Auxiliary Space Complexity: O(1), because the rotation is performed in place.
13. Check Whether a Matrix Is an Identity Matrix
An identity matrix is a square matrix in which every main diagonal element is 1 and every non-diagonal element is 0.
For every element:
- If row index equals column index, the element must be 1.
- Otherwise, the element must be 0.
C++ Program
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {
{1, 0, 0},
{0, 1, 0},
{0, 0, 1}
};
int n = 3;
bool isIdentity = true;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j && matrix[i][j] != 1) {
isIdentity = false;
}
if (i != j && matrix[i][j] != 0) {
isIdentity = false;
}
}
}
if (isIdentity) {
cout << "Identity matrix";
} else {
cout << "Not an identity matrix";
}
return 0;
}
Output
Identity matrix
Complexity Analysis
- Time Complexity: O(n²).
- Auxiliary Space Complexity: O(1).
14. Complexity Comparison of Matrix Problems
| Matrix Operation | Time Complexity | Auxiliary Space |
|---|---|---|
| Access an element | O(1) | O(1) |
| Traverse all elements | O(rows × columns) | O(1) |
| Find row and column sums | O(rows × columns) | O(1) |
| Main diagonal sum | O(n) | O(1) |
| Matrix addition | O(rows × columns) | O(rows × columns) for a separate result matrix |
| Matrix multiplication | O(m × n × p) | O(m × p) for the result matrix |
| Linear search | O(rows × columns) | O(1) |
| Search in sorted matrix | O(rows + columns) | O(1) |
| Spiral traversal | O(rows × columns) | O(1), excluding output |
| Rotate square matrix | O(n²) | O(1) |
15. Common Mistakes in Matrix Problems
- Incorrect row and column indices: Always remember that the first index represents the row and the second represents the column.
- Incorrect loop boundaries: Use the actual number of rows and columns instead of assuming every matrix is square.
- Matrix multiplication dimensions: The number of columns in the first matrix must equal the number of rows in the second matrix.
- Not initializing result matrices: Initialize multiplication result elements to zero before adding products.
- Incorrect diagonal conditions: Use i == j for the main diagonal and i + j == n - 1 for the secondary diagonal in a square matrix.
- Ignoring boundary conditions: Spiral traversal requires checking the remaining boundaries to avoid visiting elements more than once.
- Using sorted search on an unsorted matrix: The efficient top-right search requires both rows and columns to be sorted in increasing order.
- Rotating rectangular matrices in place: The simple transpose-and-reverse technique applies to square matrices.
16. Applications of Matrix Algorithms
- Image Processing: Images are often represented as matrices of pixel values.
- Computer Graphics: Matrix operations are used for rotation, scaling, and transformations.
- Game Development: Matrices represent game boards, maps, and grid-based environments.
- Artificial Intelligence: Matrix operations are widely used in machine learning computations.
- Scientific Computing: Matrices represent systems of equations and numerical data.
- Dynamic Programming: Two-dimensional tables store intermediate results in many optimization problems.
17. Interview Questions
Q1. What is a matrix?
A matrix is a rectangular arrangement of elements organized into rows and columns.
Q2. What is the difference between a square and rectangular matrix?
A square matrix has the same number of rows and columns, whereas a rectangular matrix has different numbers of rows and columns.
Q3. What is the main diagonal condition?
The main diagonal contains elements where the row index equals the column index, so i == j.
Q4. What is the secondary diagonal condition?
For an n × n matrix, the secondary diagonal contains elements satisfying i + j == n - 1.
Q5. What are the conditions for matrix multiplication?
The number of columns in the first matrix must equal the number of rows in the second matrix.
Q6. What is spiral traversal?
Spiral traversal visits matrix elements in a circular or spiral pattern, generally starting from the top-left corner.
Q7. What is the time complexity of searching a sorted matrix?
For a matrix with rows and columns sorted in increasing order, the top-right corner search takes O(rows + columns) time.
Q8. How can a square matrix be rotated 90 degrees clockwise?
First transpose the matrix, then reverse every row.
18. Practice Problems
- Print all elements of a matrix row by row.
- Print all elements column by column.
- Calculate the sum of every row and column.
- Find the largest and smallest elements in a matrix.
- Calculate the main diagonal and secondary diagonal sums.
- Add two matrices.
- Multiply two compatible matrices.
- Search for a target element in a matrix.
- Search for a target in a row-wise and column-wise sorted matrix.
- Print a matrix in spiral order.
- Rotate a square matrix 90 degrees clockwise.
- Check whether a matrix is an identity matrix.
- Check whether a matrix is symmetric.
- Find the transpose of a rectangular matrix.
19. Summary
Matrix problems are an important application of two-dimensional arrays. They involve traversing, searching, transforming, and performing mathematical operations on elements arranged in rows and columns.
- A matrix is a two-dimensional arrangement of elements.
- Nested loops are commonly used for matrix traversal.
- Main diagonal elements satisfy i == j.
- Secondary diagonal elements satisfy i + j == n - 1.
- Matrix addition requires equal dimensions.
- Matrix multiplication requires compatible dimensions.
- Sorted matrix searching can be performed in O(rows + columns).
- Spiral traversal uses four boundaries.
- A square matrix can be rotated using transpose and row reversal.