867. Transpose Matrix

Transpose Matrix (LeetCode 867) is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Array/Matrix Manipulation Patterns pattern, in the In-place Rotation subpattern.

How to solve Transpose Matrix

Transpose Matrix is a In-Place Array and Matrix Rotation problem, part of Array/Matrix Manipulation Patterns. Learn in-place rotation techniques for arrays and matrices. Rotate without using extra space.

Work towards the solution in these steps:

  1. Consider how you can represent the matrix to access its elements efficiently for manipulation.
  2. Think about what the transpose operation does to the indices of elements in a matrix.
  3. How can you use nested loops to iterate through rows and columns to build the transposed matrix?

The reference solution runs in O(r * c) time and O(1) space.

The Transpose Matrix solution and editorial walks through the full approach with reference code.

Problem statement

Given a 2D integer array matrix, return the transpose of matrix.

The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.

Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2: Input: matrix = [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]

Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 1000 1 <= m n <= 105 -109 <= matrix[i][j] <= 109

Topics and companies

Topics: Array.

Reported in interviews at Apple, Microsoft, Nvidia, Citadel.

How to practise Transpose Matrix on Thita.ai

Starter code is provided in C, C#, C++, dart, elixir, erlang, Go, Java, JavaScript, Kotlin, PHP, Python, python3, racket, Ruby, Rust, Scala, Swift and TypeScript. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(r * c) time and O(1) space.

Open Transpose Matrix in the code editor, or read the Transpose Matrix editorial for a worked solution with its approach and complexity analysis.

Where Transpose Matrix sits in the DSA pattern sheet

Problems related to Transpose Matrix

Other problems that use the same In-place Rotation and Array/Matrix Manipulation Patterns techniques:

Transpose Matrix FAQ

What is the LeetCode number of Transpose Matrix?

Transpose Matrix is LeetCode problem 867, rated Easy.

What pattern is used to solve Transpose Matrix?

Transpose Matrix is a In-Place Array and Matrix Rotation problem. It belongs to the Array/Matrix Manipulation Patterns pattern, in the In-place Rotation subpattern.

What is the time complexity of Transpose Matrix?

The reference solution runs in O(r * c) time and O(1) space.

Which companies ask Transpose Matrix?

Transpose Matrix has been reported in interviews at Apple, Microsoft, Nvidia, Citadel.

Preparing this workspace.