1. Flat Array Copy & Re-indexing
Intuition
Flatten the M x N matrix into a 1D buffer, then reconstruct the N x M transposed matrix by reading transposed indices.
Algorithm
- 1. Let m = matrix.length, n = matrix[0].length.
- 2. Flatten matrix into 1D list flat of length m * n.
- 3. Create transposed grid of dimensions n x m.
- 4. For c from 0 to n-1 and r from 0 to m-1: transposed[c][r] = flat[r * n + c].
- 5. Return transposed.
Flat Array Copy & Re-indexing
2 of 2 questions left todayPhase 1 — Flatten Source Matrix: Read all elements in row-major order: [1, 2, 3, 4, 5, 6]
Phase 1 — Flatten Source Matrix: Read all elements in row-major order: [1, 2, 3, 4, 5, 6]. Dimensions: m = 2, n = 3.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: vector<vector<int>> transpose(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<int> flat; for (int r = 0; r < m; ++r) { for (int c = 0; c < n; ++c) flat.push_back(matrix[r][c]); } vector<vector<int>> res(n, vector<int>(m)); for (int c = 0; c < n; ++c) { for (int r = 0; r < m; ++r) { res[c][r] = flat[r * n + c]; } } return res; }}; int main() { Solution sol; vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}}; vector<vector<int>> res = sol.transpose(matrix); cout << "Transposed Matrix:" << endl; for (const auto& row : res) { cout << "["; for (size_t i = 0; i < row.size(); ++i) { cout << row[i] << (i + 1 < row.size() ? ", " : ""); } cout << "]" << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(M * N)— Flattens and reconstructs all M x N elements in O(M * N) time. - Space complexity:
O(M * N)— Allocates auxiliary flat buffer of size M x N.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.