Skip to content

    Matrix Rotation & Spiral Traversal

    DSA · Intermediate

    Definition

    Matrix problems walk a 2D array in special orders such as spiral, or transform it such as rotating 90°.

    Common warm-up questions that test index control.

    Diagram

    1 2 34 5 67 8 9spiral: 1 2 3 6 9 8…

    Flowchart

    Set top, bottom, left, right boundsWalk right, down, left, upShrink boundsStop when bounds cross

    Example: Rotate 90° clockwise

    m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    print([list(r) for r in zip(*m[::-1])])

    Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

    Complexity

    O(rows × cols)

    Key points

    • Rotate = transpose + reverse rows
    • Track bounds carefully for spiral

    Interview questions

    Rotate in place?

    Transpose the matrix, then reverse each row.

    More DSA topics