Introduction
Transpose Matrix means converting:
- rows into columns
- columns into rows
inside a matrix.
The task is to:
- swap matrix elements
- transform matrix structure
- transpose efficiently
Example:
Input Matrix:
1 2 3
4 5 6
7 8 9
Transpose Matrix:
1 4 7
2 5 83 6 9
Explanation:
Rows become columns after transpose operation. This problem is one of the most important applications of:
Matrix ManipulationConstraints
1 <= Matrix Size <= 10^3Approach 1 : Brute Force (Using Extra Matrix)
Explanations:
Explanation:
The idea is:
- create new matrix
- place transposed elements correctly
Steps:
- Traverse matrix.
- Swap row and column positions.
- Store in new matrix.
This approach works but:
- uses extra space
So in-place transpose is preferred.
Dry Run
Input:1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
Practice :
Complexity Analysis :
Time Complexity:- O(n²)Explanation : Every matrix element is visited once.
Space Complexity:- O(n²)
Explanation :
Extra matrix is used.
Approach 2 : Optimal Solution(In-Place Transpose)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- swap upper triangle elements
- perform transpose in-place
This avoids:
- extra matrix usage
Dry Run
Input:1 2 3
4 5 6
7 8 9
Swap:
2 with 4
Swap:
3 with 7
Swap:
6 with 8
Output:
1 4 7
2 5 8
3 6 9
Practice :