Data Structures & AlgorithmsVery hardProduct Company SDE · matrix simulation

Problem: What is the spiral (clockwise from the top-left) traversal of the matrix [[1,2,3],[4,5,6],[7,8,9]]? Print the list produced by the code.

Problem: What is the spiral (clockwise from the top-left) traversal of the matrix [[1,2,3],[4,5,6],[7,8,9]]? Print the list produced by the code.
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
out = []
top, bot, left, right = 0, 2, 0, 2
while top <= bot and left <= right:
    out += M[top][left:right + 1]
    top += 1
    out += [M[r][right] for r in range(top, bot + 1)]
    right -= 1
    if top <= bot:
        out += M[bot][left:right + 1][::-1]
        bot -= 1
    if left <= right and top <= bot:
        out += [M[r][left] for r in range(bot, top - 1, -1)]
        left += 1
print(out)
What is printed?
  1. A. [1, 2, 3, 6, 9, 8, 7, 5, 4]
  2. B. [1, 4, 7, 8, 9, 6, 3, 2, 5]
  3. C. [1, 2, 3, 6, 9, 8, 7, 4]
  4. D. [1, 2, 3, 6, 9, 8, 7, 4, 5]

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

The boundaries shrink after each side, which yields 1, 2, 3, then 6, 9, then 8, 7, then 4, and finally the centre 5.

More Coding Interview Problems questions

Exams that ask this topic