Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Print a matrix in spiral order.

Problem: Print a matrix in spiral order.
def spiral(m):
    res = []
    while m:
        res += m.pop(0)
        m = [list(r) for r in zip(*m)][::-1]
    return res
print(spiral([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]))
What is printed?
  1. A. [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 8, 5]
  2. B. [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8]
  3. C. [1, 2, 3, 6, 9, 12, 10, 11, 7, 4, 5, 8]
  4. D. [1, 4, 7, 10, 11, 12, 9, 6, 3, 2, 5, 8]

Correct answer: B. [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8]

Take the top row, then rotate the rest counter-clockwise so the right column becomes the new top row. For the 4 × 3 matrix this yields 1 2 3, then 6 9 12, then 11 10, then 7 4, and finally 5 8.

More Coding Interview Problems questions

Exams that ask this topic