medium
0 views

Matrix Transpose

Given a matrix of R rows and C columns, print its transpose where rows become columns and vice versa.

Understand the Problem

Problem Statement

Given a matrix of R rows and C columns as the input, the program must print the transpose of the input matrix.

The transpose of a matrix is obtained by swapping rows with columns. The element at position (i, j) in the original matrix becomes the element at position (j, i) in the transposed matrix.

Constraints

  • 1 <= R, C <= 1000
  • Matrix elements can be any valid integers
  • Memory constraints must be considered for large matrices
  • Time complexity should be O(R × C)

Examples

Example 1
Input
4 3
62 9 88
72 81 31
3 99 72
3 64 51
Output
62 72 3 3
9 81 99 64
88 31 72 51
Explanation

The original 4×3 matrix is transposed into a 3×4 matrix. The first column of the original (62, 72, 3, 3) becomes the first row of the transpose. Similarly, the second column (9, 81, 99, 64) becomes the second row, and the third column (88, 31, 72, 51) becomes the third row.

Example 2
Input
3 3
1 2 3
4 5 6
7 8 9
Output
1 4 7
2 5 8
3 6 9
Explanation

The original 3×3 matrix is transposed into another 3×3 matrix. The first column (1, 4, 7) becomes the first row, the second column (2, 5, 8) becomes the second row, and the third column (3, 6, 9) becomes the third row.

Solution

#include <stdio.h>

int main() {
    int r, c;
    scanf("%d %d", &r, &c);
    
    int matrix[r][c];
    
    // Read the matrix
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Print transpose
    for (int j = 0; j < c; j++) {
        for (int i = 0; i < r; i++) {
            printf("%d", matrix[i][j]);
            if (i < r - 1) {
                printf(" ");
            }
        }
        printf("\n");
    }
    
    return 0;
}
Time:O(R × C) - We need to access each element once to read it and once to print it in transpose order
Space:O(R × C) - We store the entire matrix in memory to perform the transpose
Approach:

Step-by-step explanation:

  1. Read R and C from standard input using scanf
  2. Declare a 2D array with dimensions R×C using variable-length array syntax
  3. Use nested loops to read all matrix elements: outer loop for rows, inner loop for columns
  4. For transpose: swap the loop order - outer loop iterates through columns (0 to C-1), inner loop iterates through rows (0 to R-1)
  5. Print each element matrix[i][j] followed by a space (except for the last element in each row)
  6. After printing all elements of a column (which becomes a row in transpose), print a newline

Visual Explanation

Loading diagram...