Tutorialspoint
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)
ArraysControl StructuresCognizantTech Mahindra
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Define a function transposeMatrix that takes a 2D array and its dimensions.
 Step 2: Create a new array with reversed dimensions to store the transposed matrix.
 Step 3: Use nested loops to exchange rows and columns of the original matrix.
 Step 4: Store matrix[i][j] in transposed[j][i] for each element.
 Step 5: Print the transposed matrix.
 Step 6: In main, create a matrix and call the function.

Submitted Code :