
Problem
Solution
Submissions
Transpose a Matrix
Certification: Basic Level
Accuracy: 18.18%
Submissions: 11
Points: 5
Write a C# program to find the transpose of a given matrix. The transpose of a matrix is obtained by switching its rows with its columns. If the original matrix is of dimension m×n, then the transposed matrix will be of dimension n×m.
Example 1
- Input: matrix = [
[1, 2, 3],
[4, 5, 6] ] - Output: [
[1, 4],
[2, 5],
[3, 6] ] - Explanation:
- Step 1: Determine the dimensions of the original matrix (2 rows × 3 columns).
- Step 2: Create a new matrix with swapped dimensions (3 rows × 2 columns).
- Step 3: For each element at position (i,j) in the original matrix, place it at position (j,i) in the new matrix.
- Step 4: The original matrix is 2×3, so its transpose is 3×2. Each element at position (i,j) in the original matrix is placed at position (j,i) in the transposed matrix.
Example 2
- Input: matrix = [
[1, 2],
[3, 4],
[5, 6] ] - Output: [
[1, 3, 5],
[2, 4, 6] ] - Explanation:
- Step 1: Determine the dimensions of the original matrix (3 rows × 2 columns).
- Step 2: Create a new matrix with swapped dimensions (2 rows × 3 columns).
- Step 3: For each element at position (i,j) in the original matrix, place it at position (j,i) in the new matrix.
- Step 4: The original matrix is 3×2, so its transpose is 2×3. The rows of the original matrix become the columns of the transposed matrix.
Constraints
- 1 ≤ matrix.length ≤ 100
- 1 ≤ matrix[i].length ≤ 100
- -1000 ≤ matrix[i][j] ≤ 1000
- Time Complexity: O(m*n)
- Space Complexity: O(m*n)
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 (n×m instead of m×n).
- Iterate through the original matrix and swap the row and column indices when populating the new matrix.
- Ensure proper handling of non-square matrices.
- Use a nested loop to access each element in the original matrix.
- Assign each element to its new position in the transposed matrix.