
Problem
Solution
Submissions
Transpose of a Matrix
Certification: Basic Level
Accuracy: 23.08%
Submissions: 13
Points: 10
Write a C++ program that finds the transpose of a given 2D matrix. The transpose of a matrix is obtained by flipping the matrix over its diagonal, and switching the row and column indices of the matrix.
Example 1
- Input: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9] ] - Output: [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9] ] - Explanation:
- Step 1: Create a new matrix with dimensions swapped (rows become columns, columns become rows).
- Step 2: For each element at position (i, j) in the original matrix, place it at position (j, i) in the new matrix.
- Step 3: Return the transposed matrix.
Example 2
- Input: matrix = [
[1, 2],
[3, 4] ] - Output: [
[1, 3],
[2, 4] ] - Explanation:
- Step 1: Create a new matrix with dimensions swapped (2×2 remains 2×2 for a square matrix).
- Step 2: For each element at position (i, j) in the original matrix, place it at position (j, i) in the new matrix.
- Step 3: Return the transposed matrix.
Constraints
- 1 ≤ rows, cols ≤ 1000
- Matrix elements are integers
- Time Complexity: O(n*m), where n is the number of rows and m is the number of columns
- Space Complexity: O(n*m)
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
- Create a new matrix with dimensions swapped (rows become columns and vice versa).
- Iterate through the original matrix and fill the new matrix accordingly.
- Handle edge cases where the matrix is empty or has only one element.