Hone logo
Hone
Problems

Spiral Matrix Traversal

This challenge involves generating a two-dimensional matrix filled with sequential numbers in a spiral pattern. This is a common problem that tests your ability to manage array indices and control flow, often appearing in coding interviews. Understanding how to traverse data structures in specific patterns is a fundamental skill in computer science.

Problem Description

Given an integer n, generate a n x n matrix filled with elements from 1 to n^2 in a spiral order.

You will need to:

  • Create an n x n matrix.
  • Populate this matrix with integers starting from 1 up to n^2.
  • Fill the matrix in a clockwise spiral pattern, moving from left to right, then top to bottom, then right to left, then bottom to top, and so on, until all cells are filled.

Key Requirements:

  • The matrix must be square (n x n).
  • Numbers must be sequential integers from 1 to n^2.
  • The filling order must strictly follow a clockwise spiral.

Expected Behavior: The output should be a 2D array (matrix) representing the filled spiral.

Edge Cases to Consider:

  • n = 1: A single cell matrix.
  • n = 0: An empty matrix.

Examples

Example 1:

Input: n = 3
Output:
[
  [1, 2, 3],
  [8, 9, 4],
  [7, 6, 5]
]
Explanation: The numbers are filled in a spiral pattern:
1 -> 2 -> 3 (right)
           |
           4 (down)
           |
3 <- 9     4
|    |     |
7 <- 6 <- 5 (left)
|
8 (up)
|
1 (back to start)

Example 2:

Input: n = 1
Output:
[
  [1]
]
Explanation: A 1x1 matrix only contains the number 1.

Example 3:

Input: n = 4
Output:
[
  [ 1,  2,  3,  4],
  [12, 13, 14,  5],
  [11, 16, 15,  6],
  [10,  9,  8,  7]
]
Explanation: Similar to Example 1, but for a larger matrix.

Constraints

  • 0 <= n <= 100
  • The input n will be an integer.
  • The output should be a 2D array of integers.
  • The solution should aim for optimal time complexity, ideally O(n^2).

Notes

Think about how you can keep track of the boundaries of the current layer of the spiral you are filling. You might need variables to represent the top row, bottom row, left column, and right column that are currently being processed. Also, consider how to change direction once a boundary is reached.

Loading editor...
plaintext