Transpose of a Matrix

easy Matrix (2D arrays)

Problem

Read a matrix with r rows and c columns. Print its transpose: the element in row i and column j moves to row j and column i. The result has c rows and r columns.

Constraints

  • 1 <= r, c <= 100

Examples

Input

2 3
1 2 3
4 5 6

Output

1 4
2 5
3 6

Solutions

Best approachTime O(r * c)Space O(r * c)

In the transpose, rows become columns. The element at (i, j) goes to (j, i). For a non-square matrix the shape changes from r x c to c x r.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process a matrix.
 * Input   : r and c, then r rows of c integers.
 * Output  : The transposed matrix.
 * Approach: Swap row and column.
 * Time    : O(r * c)
 * Space   : O(r * c)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(int[][] m) {
        int rows = m.length;
        int cols = m[0].length;

        // Step 1: The new matrix has cols rows and rows columns.
        int[][] result = new int[cols][rows];

        // Step 2: Copy every element from position (i, j) to position (j, i).
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[j][i] = m[i][j];
            }
        }

        // Step 3: Make one line of text for each new row.
        String[] lines = new String[cols];
        for (int j = 0; j < cols; j++) {
            StringBuilder line = new StringBuilder();
            for (int i = 0; i < rows; i++) {
                if (i > 0) {
                    line.append(" ");
                }
                line.append(result[j][i]);
            }
            lines[j] = line.toString();
        }
        return lines;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int rows = scanner.nextInt();
        int cols = scanner.nextInt();
        int[][] m = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                m[i][j] = scanner.nextInt();
            }
        }
        System.out.println(String.join("\n", solve(m)));
    }
}
Hints (1)
  1. What is the shape of the result for a 2 x 3 matrix?