Python 0867.py
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
for i in range(len(matrix[0])):
yield [ matrix[j][i] for j in range(len(matrix)) ]
Difficulty
and has an acceptance rate of about 77% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method transpose. The method receives a two-dimensional list matrix and produces the transpose of that matrix by yielding each row of the transposed result one at a time. The use of a generator (yield) means that the caller can iterate over the transposed rows without the need to allocate a complete new matrix in memory.
Core Logic
The heart of the algorithm is a for loop that iterates over the column indices of the original matrix. For each column index i, a list comprehension collects the elements from every row j at that column position, forming one row of the transposed matrix. The resulting list is then emitted with yield.
for i in range(len(matrix[0])):
yield [matrix[j][i] for j in range(len(matrix))]
Iteration Over Columns
The outer loop uses range(len(matrix[0])) to determine how many columns exist in the input. This drives the number of rows that will appear in the transposed output.
Construction of a Transposed Row
Inside the loop, the list comprehension [matrix[j][i] for j in range(len(matrix))] walks through each original row j and extracts the element at column i. The comprehension builds a new list that represents one row of the transposed matrix.
Edge Cases Handled
When the input matrix contains a single row, len(matrix[0]) equals the number of elements in that row, and the outer loop runs once for each element. The list comprehension then iterates over the single row, producing a column-wise view that matches the expected transpose of a 1 × N matrix.
When the input matrix contains a single column, len(matrix[0]) is 1, so the outer loop executes exactly once. The inner comprehension iterates over all rows, gathering the sole element from each row into a list that becomes the only row of the transposed output, effectively converting an N × 1 matrix into a 1 × N matrix.
The algorithm also works correctly for rectangular matrices where the number of rows differs from the number of columns, as the outer loop is driven by the column count and the inner loop by the row count, ensuring every element is visited exactly once.
Performance Characteristics
By employing a generator, the method avoids constructing the entire transposed matrix up front. This lazy evaluation reduces peak memory usage, especially beneficial when the caller processes each transposed row sequentially and does not need the whole result simultaneously.
The list comprehension inside the generator is a compact and efficient way to gather elements for each transposed row. It leverages Python’s internal optimizations for list building, minimizing overhead compared to manual element appends inside a loop.
Using range with the lengths of the matrix dimensions provides direct integer iteration without additional function calls, contributing to a streamlined execution path.
Overall, the design balances clarity with resource efficiency, delivering a transposition operation that scales well with the size of the input matrix while keeping the implementation succinct.
ELI5 - Simplified Explanation
Imagine you have a flat tray filled with square building blocks arranged in rows and columns, just like a grid made of toy bricks. The code looks at every column in the tray one by one. For each column, it picks up all the blocks from top to bottom and lays them out in a new row for a different tray. This means the tall stacks of blocks turn into long lines of blocks. If a tray had three rows of blocks, the new tray will now have three columns instead. It is like tilting the original tray so that everything sideways moves to become tall, and everything tall moves to become sideways.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | JS | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 836: Rectangle Overlap
- problem 2824: Count Pairs Whose Sum is Less than Target
- problem 475: Heaters
- problem 672: Bulb Switcher II
- problem 1461: Check If a String Contains All Binary Codes of Size K
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality