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?- A. [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 8, 5]
- B. [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8]
- C. [1, 2, 3, 6, 9, 12, 10, 11, 7, 4, 5, 8]
- 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
- Problem: Run Conway's Game of Life on an unbounded board (a live cell survives with 2 or 3 live neighbours; a dead cell becomes live with…
- In the Tower of Hanoi with 5 discs and 3 pegs A, B, C in a row, moves are allowed only between ADJACENT pegs (A↔B, B↔C, never A↔C…
- Problem: Count the integers in [1, 1000] that are coprime to 1000. python from math import gcd print(sum(1 for i in range(1, 1001) if…
- Reservoir sampling keeps k = 2 items from a stream of n = 10 items: the first 2 fill the reservoir, and item i (i > 2) is admitted with…
- Problem: An LFU cache (capacity 2) evicts the least frequently used key; ties are broken by least recently used. get returns −1 on a miss…
- Edge case: A generator expression is consumed twice. python g = (x x for x in range(4)) print(sum(g), sum(g)) What is printed?