Swap Row and Column Indices of a Rectangular Matrix

Quick Overview

Swap Row and Column Indices of a Rectangular Matrix. Return the transpose of matrix: the value at input row r, column c must appear at output row c, column r.

Swap Row and Column Indices of a Rectangular Matrix

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem Return the transpose of `matrix`: the value at input row r, column c must appear at output row c, column r. An m-by-n input therefore produces an n-by-m matrix. ```cpp class Solution { public: vector<vector<int>> transpose(vector<vector<int>>& matrix); }; ``` ### Examples **Example 1:** ```text Input: matrix = [[2,-1,4],[7,0,5]] Output: [[2,7],[-1,0],[4,5]] Explanation: Each input column becomes one output row. ``` **Example 2:** ```text Input: matrix = [[9],[3],[6]] Output: [[9,3,6]] Explanation: A three-row column becomes a one-row matrix. ``` ### Constraints - `m == matrix.length`, `n == matrix[i].length`. - `1 <= m,n <= 1000` and `1 <= m*n <= 10^5`. - `-10^9 <= matrix[i][j] <= 10^9`. ### Contract considerations The input is rectangular, and transposition changes positions rather than element values. ```hint Read the boundary condition Write the output dimensions before choosing loop bounds. ``` ### Boundary reminders The input is rectangular, and transposition changes positions rather than element values.

Overview: Swap Row and Column Indices of a Rectangular Matrix. Return the transpose of matrix: the value at input row r, column c must appear at output row c, column r.

Amazon logo
Amazon
Source window: 0–3 months · as of Oct 21, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the transpose of matrix: the value at input row r, column c must appear at output row c, column r. An m-by-n input therefore produces an n-by-m matrix.

class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& matrix);
};

Examples

Example 1:

Input: matrix = [[2,-1,4],[7,0,5]]
Output: [[2,7],[-1,0],[4,5]]
Explanation: Each input column becomes one output row.

Example 2:

Input: matrix = [[9],[3],[6]]
Output: [[9,3,6]]
Explanation: A three-row column becomes a one-row matrix.

Constraints

  • m == matrix.length , n == matrix[i].length .
  • 1 <= m,n <= 1000 and 1 <= m*n <= 10^5 .
  • -10^9 <= matrix[i][j] <= 10^9 .

Contract considerations

The input is rectangular, and transposition changes positions rather than element values.

Boundary reminders

The input is rectangular, and transposition changes positions rather than element values.