Transpose a Matrix(UPI) - codepath/compsci_guides GitHub Wiki
TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Matrix, 2D Array Manipulation
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What is the input to the function?
- A: The input is a 2D integer array
matrix
.
- A: The input is a 2D integer array
-
Q: What is the expected output of the function?
- A: The function should return the transpose of the input matrix, which is the matrix flipped over its main diagonal, swapping rows and columns.
-
Q: What should the function return if the matrix is empty?
- A: If the matrix is empty or contains no rows, the function should return an empty list.
-
Q: What are the dimensions of the transposed matrix?
- A: If the original matrix has dimensions
m x n
, the transposed matrix will have dimensionsn x m
. markdown Copy code
- A: If the original matrix has dimensions
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: To transpose the matrix, we need to swap its rows and columns. This involves iterating over each element in the matrix and placing it in the appropriate position in the transposed matrix.
1) Check if the input matrix is empty. If it is, return an empty list.
2) Determine the number of rows and columns in the original matrix.
3) Initialize an empty 2D list `transposed_matrix` with dimensions `cols x rows`.
4) Iterate over each element in the original matrix:
- Place each element `matrix[i][j]` into `transposed_matrix[j][i]`.
5) Return the `transposed_matrix` after filling it with the appropriate values.
markdown
⚠️ Common Mistakes
- Not correctly handling cases where the input matrix is empty or has no columns.
- Confusing the dimensions when initializing the transposed matrix.
- Incorrectly swapping indices while filling the transposed matrix. markdown
I-mplement
def transpose(matrix):
if not matrix or not matrix[0]:
return []
rows = len(matrix)
cols = len(matrix[0])
# Initialize the transposed matrix with the flipped dimensions
transposed_matrix = [[0] * rows for _ in range(cols)]
for i in range(rows):
for j in range(cols):
transposed_matrix[j][i] = matrix[i][j]
return transposed_matrix