TIP102 Unit 1 Session 2 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the input to the function?
matrix
.Q: What is the expected output of the function?
Q: What should the function return if the matrix is empty?
Q: What are the dimensions of the transposed matrix?
m x n
, the transposed matrix will have dimensions n x m
.
markdown
Copy code
## P-lanPlan 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
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