Ctrl K

Pour a List Into a Spiral

Medium
You are given the size of a table, rows × cols, and the head head of a singly linked list of non-negative integers. Fill the table with the list's values in order, moving in a spiral: start at the top-left corner going right, and turn clockwise at an edge or in front of an already filled cell. If the values run out before the cells do, every unfilled cell must hold -1. Return the resulting table.
Example 1
rows=3, cols=3, head=list_node([4, 0, 7, 2, 9, 5]) → [[4, 0, 7], [-1, -1, 2], [-1, 5, 9]]

The top row gets 4, 0, 7; the right column below it gets 2 and 9; then 5 lands in the middle of the bottom row. The other three cells stay -1.

Example 2
rows=2, cols=2, head=list_node([8, 3, 6, 1]) → [[8, 3], [1, 6]]

There are exactly as many values as cells: 8 and 3 on top, 6 in the bottom-right corner, 1 to its left.

Example 3
rows=1, cols=4, head=list_node([10]) → [[10, -1, -1, -1]]
Constraints
  • 1 ≤ rows, cols
  • rows · cols ≤ 10⁵
  • The list has between 1 and rows · cols nodes
  • 0 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSpiral Readout MediumSpiral-Numbered Square MediumNext Step of a Cell Colony MediumZigzag Diagonal Sweep MediumMatch-Three Cascade Medium
loading Python…
Input
rows=3, cols=3, head=list_node([4, 0, 7, 2, 9, 5])
Expected
[[4, 0, 7], [-1, -1, 2], [-1, 5, 9]]

Run checks the first 3 tests in your browser. Submit checks all 101 tests on the server, hidden ones included.