Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Rotate an n × n image 90° clockwise in place.

Problem: Rotate an n × n image 90° clockwise in place.
def rotate(m):
    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()
    return m
print(rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
What is printed?
  1. A. [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
  2. B. [[3, 6, 9], [2, 5, 8], [1, 4, 7]]
  3. C. [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  4. D. [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

Correct answer: A. [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

Transpose, then reverse each row = clockwise rotation. Transpose then reverse the column order of rows (or reverse rows first) gives counter-clockwise [[3,6,9],…]. The j loop starts at i + 1 so each pair is swapped once; starting at 0 would swap twice and undo the transpose. O(n²), O(1) space.

More Coding Interview Problems questions

Exams that ask this topic