Data Structures & AlgorithmsModerateFlipkart/Uber OA · placement

Rotate a square matrix 90° clockwise in place by transposing and then reversing each row. What is printed?

Rotate a square matrix 90° clockwise in place by transposing and then reversing each row. What is printed?
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = len(m)
for i in range(n):
    for j in range(i + 1, n):
        m[i][j], m[j][i] = m[j][i], m[i][j]
for row in m: row.reverse()
print(m[0], m[2])
  1. A. [3, 6, 9] [1, 4, 7]
  2. B. [7, 1, 4] [9, 6, 3]
  3. C. [7, 4, 1] [9, 3, 6]
  4. D. [7, 4, 1] [9, 6, 3]

Correct answer: D. [7, 4, 1] [9, 6, 3]

Transpose then reverse each ROW gives a clockwise rotation; transpose then reverse the row ORDER gives anticlockwise. Output: [7, 4, 1] [9, 6, 3].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic