I want to rotate (anti-clockwise) a 2D nxn array of integers and the 2D array is stored as a list of lists.
For example:
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
After rotation, the output should look like:
b = [[3, 6, 9],
[2, 5, 8],
[1, 4, 7]]
I have written a function which performs the above rotation:
def rotate_clockwise(matrix):
transposed_matrix = zip(*matrix) # transpose the matrix
return list(map(list, reversed(transposed_matrix))) # reverse the transposed matrix
The function works well and the code looks pretty Pythonic to me. However, I am having trouble understanding the space and time complexity of my solution.
Can someone explain both the complexities of the constructs I have used, namely zip(*matrix)
, reversed(list)
, map(list, iterator)
and list(iterator)
?
How can I make this code more efficient? Also, what would be the most efficient way to rotate a 2D matrix?
NOTE: As mentioned by @Colonder in the comments, there might be a similar question to this. However, this question focuses more on discussing the space and time complexities of the problem.