Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

Print a matrix in spiral order (right, down, left, up, repeat). What is printed?

Print a matrix in spiral order (right, down, left, up, repeat). What is printed?
m = [[50, 81, 32, 23], [30, 61, 32, 23], [60, 51, 32, 43]]
top, bot, l, r, out = 0, len(m) - 1, 0, len(m[0]) - 1, []
while top <= bot and l <= r:
    out += m[top][l:r + 1]; top += 1
    out += [m[i][r] for i in range(top, bot + 1)]; r -= 1
    if top <= bot: out += m[bot][l:r + 1][::-1]; bot -= 1
    if l <= r: out += [m[i][l] for i in range(bot, top - 1, -1)]; l += 1
print(out[6:6 + 4])
  1. A. [60, 51, 32, 30]
  2. B. [32, 51, 60, 30]
  3. C. [32, 51, 30, 60]
  4. D. [32, 60, 51, 30]

Correct answer: B. [32, 51, 60, 30]

The bottom row is read right-to-left and the left column bottom-to-top; the guards stop a single remaining row or column from being read twice. Output: [32, 51, 60, 30].

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

Exams that ask this topic