Spiral Number Grid Printer

Hard ⏱ 18 min 35% acceptance ★★★★★ 4.5
Write a function spiral_grid(n) that returns an n x n 2D list filled with the numbers 1 to n*n arranged in a clockwise spiral starting from the top-left corner, built using loops that walk the four boundary directions (right, down, left, up) and shrink the boundary each pass.

Examples

Example 1
Input
spiral_grid(3)
Output
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Explanation

Numbers spiral clockwise inward from the top-left.

Constraints

  • n is a positive integer.

Topics

Loopsnested loopswhile loop

Companies

GoogleAtlassian

Hints

Hint 1

Track four boundaries: top, bottom, left, right, and shrink each after traversing it.

Hint 2

Walk right across the top row, down the right column, left across the bottom row, and up the left column, in a loop that repeats until all cells are filled.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.