Skip to main content
mediumBlind 75

Spiral Matrix

Given an m x n matrix, return all elements in spiral order Traverse: right → down → left → up → repeat inward Example: [[1,2,3],[4,5,6],[7,8,9]] => [1,2,3,6,9,8,7,4,5]

Spiral Matrix turns a simple directional walk into careful boundary bookkeeping: sweep right, down, left, and up, tightening the four edges after each pass. The edge cases worth walking by hand are rectangular matrices where the final sweep is a single row or column.

Examples

You write

spiral_order(matrix: List[List[int]])

  1. Example 1

    Input
    matrix = [[1,2,3],[4,5,6],[7,8,9]]
    returns
    [1,2,3,6,9,8,7,4,5]
  2. Example 2

    Input
    matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
    returns
    [1,2,3,4,8,12,11,10,9,5,6,7]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Spiral Matrix Traversalmedium

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.