AlgoTales · Roadmap

Transpose

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Transposing a grid swaps its rows and columns, so the cell in row 2, column 5 moves to row 5, column 2. The data does not change, only the direction you read it. It is how reports and spreadsheets are turned on their side.

Practical use cases

  • Web app: Class timetable turned around. A school portal stores a timetable with days as rows and periods as columns. A teacher asks for the other view: periods as rows and days as columns. Transposing the same data produces it, with no need to query the database again.
  • Web app: Pivoting a report in an admin dashboard. A sales report has one row per month and one column per product, but the manager wants one row per product. A transpose of the table gives the new layout, and a toggle button in the page can switch back and forth instantly.
  • System: Spreadsheets and machine learning. Spreadsheet paste-special has a transpose option, and numeric libraries transpose data tables before calculations, because many formulas need rows and columns swapped to line up properly. Built-in support saves developers from hand-writing fiddly nested loops.

The story: Mrs. Sharma's Timetable Flip

Mrs. Sharma pinned a timetable on the staff-room wall. Each row was a day, each column was a period. Monday: Maths, Hindi, Art. Tuesday: Science, PT, Music. The class teachers loved it.

But the art teacher, Mr. Das, groaned. "I teach only in period 3. I want to look down one column per period, not hunt across every row!" He asked Mira to prepare a new timetable where periods are rows and days are columns.

Mira did not rewrite anything creatively. She followed one simple rule: the item at row i, column j in the old table goes to row j, column i in the new one. The first row became the first column. The second row became the second column. Rows and columns had swapped jobs!

That flip is a matrix transpose. A 2 × 3 table becomes a 3 × 2 table. For a square table, you can even do it in place by swapping each pair of cells across the diagonal. You will meet transposes whenever data needs to be viewed "the other way round".

How to spot this problem, and where you need it

Your data is laid out with rows and columns the wrong way round for the screen, export or calculation you need, and looping manually to rebuild it is messy.

Signs you need it

  • A customer asks for the same table with rows and columns swapped, or an export arrives sideways.
  • Your code loops over columns first and rows second, so you keep mixing up i and j.
  • The problem says transpose, flip along the diagonal, or convert row-wise data to column-wise.

Where to use it in a project

  • Admin reports, timetables and comparison tables where users toggle between two orientations.
  • Preparing data for charts, CSV export and matrix calculations that expect the other layout.

The solution

For a table with R rows and C columns, build a new table with C rows and R columns. For every position in the old table, copy the value at row i, column j into row j, column i of the new table. For a square grid you can do it in place by swapping each cell above the diagonal with its mirror, visiting every pair once.

Payoff: Before: duplicate database queries and templates for two layouts. After: one dataset and a quick swap shows either view.

Explain it like I am 8

You have a chocolate tray with 2 rows of 3 chocolates. Now tilt your head sideways and read it again: you see 3 rows of 2. The chocolates did not change, only the direction you read them did.

How it works, step by step

  1. Make a new empty table with the dimensions swapped: rows become columns.
  2. Walk through every cell of the old table: row i, column j.
  3. Copy it to the new table at new[j][i].
  4. For a square matrix you can skip the new table: swap m[i][j] with m[j][i] for every j > i (only above the diagonal, or you will undo your own work).
  5. Check: the first row of the old table is now the first column of the new one.

The code in four languages

PHP

<?php
// Transpose any rows x cols table into a cols x rows table
function transpose(array $a): array {
    $rows = count($a);
    $cols = count($a[0]);
    $t = [];
    for ($j = 0; $j < $cols; $j++) {          // new rows
        for ($i = 0; $i < $rows; $i++) {      // new columns
            $t[$j][$i] = $a[$i][$j];           // swap the two numbers
        }
    }
    return $t;
}

$timetable = [['Mat', 'Hin', 'Art'], ['Sci', 'PT', 'Mus']];
foreach (transpose($timetable) as $row) {
    echo implode(' ', $row) . PHP_EOL;
}
// Mat Sci
// Hin PT
// Art Mus

JavaScript

// Transpose any rows x cols table into a cols x rows table
function transpose(a) {
  const rows = a.length;
  const cols = a[0].length;
  const t = [];
  for (let j = 0; j < cols; j++) {            // new rows
    t.push([]);
    for (let i = 0; i < rows; i++) {          // new columns
      t[j][i] = a[i][j];                      // swap the two numbers
    }
  }
  return t;
}

const timetable = [['Mat', 'Hin', 'Art'], ['Sci', 'PT', 'Mus']];
for (const row of transpose(timetable)) {
  console.log(row.join(' '));
}
// Mat Sci
// Hin PT
// Art Mus

Java

public class Main {
    // Transpose any rows x cols table into a cols x rows table
    static String[][] transpose(String[][] a) {
        int rows = a.length;
        int cols = a[0].length;
        String[][] t = new String[cols][rows];
        for (int j = 0; j < cols; j++) {          // new rows
            for (int i = 0; i < rows; i++) {      // new columns
                t[j][i] = a[i][j];                // swap the two numbers
            }
        }
        return t;
    }

    public static void main(String[] args) {
        String[][] timetable = {{"Mat", "Hin", "Art"}, {"Sci", "PT", "Mus"}};
        for (String[] row : transpose(timetable)) {
            System.out.println(String.join(" ", row));
        }
        // Mat Sci
        // Hin PT
        // Art Mus
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// transpose turns a rows x cols table into a cols x rows table.
func transpose(a [][]string) [][]string {
	rows := len(a)
	cols := len(a[0])
	t := make([][]string, cols)
	for j := 0; j < cols; j++ { // new rows
		t[j] = make([]string, rows)
		for i := 0; i < rows; i++ { // new columns
			t[j][i] = a[i][j] // swap the two numbers
		}
	}
	return t
}

func main() {
	timetable := [][]string{{"Mat", "Hin", "Art"}, {"Sci", "PT", "Mus"}}
	for _, row := range transpose(timetable) {
		fmt.Println(strings.Join(row, " "))
	}
	// Mat Sci
	// Hin PT
	// Art Mus
}

Time: O(rows × cols) · Extra space: O(rows × cols). Each item is copied once into the new table. A square matrix can be done in place with O(1) extra space.

Watch out for

  • Reusing the same dimensions for the new table. A 2 × 3 matrix becomes 3 × 2.
  • In-place square transpose: swapping every pair twice (once from each side), which puts everything back. Only swap when j > i.
  • Mixing up [i][j] and [j][i] while copying.

Quick check

  1. The transpose of a 2 × 3 table has what shape?
    • 2 × 3
    • 3 × 2
    • 6 × 1
  2. Where does the item at row 0, column 2 go?
    • Row 2, column 0
    • Row 0, column 2
    • Row 1, column 1
  3. For an in-place square transpose, which cells do you swap?
    • All pairs, from both sides
    • Only pairs with j greater than i
    • Only the diagonal