{"id":"6b093ddfbd4755deb67ee0a1","slug":"spiral-matrix","title":"Spiral matrix","summary":"Read the elements of a matrix clockwise, from the outside to the centre. A task about keeping boundaries in check rather than about a clever algorithm.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["arrays","matrix","simulation"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** Returns all elements of the matrix in clockwise spiral order. */\nfunction spiralOrder(matrix: number[][]): number[] {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('3 × 3', () => {\n  expect(spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]])).toEqual([1, 2, 3, 6, 9, 8, 7, 4, 5]);\n});\n\ntest('3 × 4 (wider than tall)', () => {\n  expect(spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])).toEqual([1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]);\n});\n\ntest('4 × 2 (taller than wide)', () => {\n  expect(spiralOrder([[1, 2], [3, 4], [5, 6], [7, 8]])).toEqual([1, 2, 4, 6, 8, 7, 5, 3]);\n});\n\ntest('single row and single column', () => {\n  expect(spiralOrder([[1, 2, 3]])).toEqual([1, 2, 3]);\n  expect(spiralOrder([[1], [2], [3]])).toEqual([1, 2, 3]);\n  expect(spiralOrder([[42]])).toEqual([42]);\n});\n\ntest('empty matrices', () => {\n  expect(spiralOrder([])).toEqual([]);\n  expect(spiralOrder([[]])).toEqual([]);\n});\n\ntest('5 × 3 with a single middle column left', () => {\n  const m = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]];\n  expect(spiralOrder(m)).toEqual([1, 2, 3, 6, 9, 12, 15, 14, 13, 10, 7, 4, 5, 8, 11]);\n});\n\ntest('performance: 500 × 500', () => {\n  const n = 500;\n  const m = Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => r * n + c));\n  const got = spiralOrder(m);\n  expect(got).toHaveLength(n * n);\n  expect(got.slice(0, 3)).toEqual([0, 1, 2]);\n  expect(got[n]).toBe(2 * n - 1);\n  expect(got[n * n - 1]).toBe(250 * n + 249);\n  expect(got.reduce((a, b) => a + b, 0)).toBe(((n * n - 1) * n * n) / 2);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Returns all elements of the matrix in clockwise spiral order.\n * @param {number[][]} matrix\n * @returns {number[]}\n */\nfunction spiralOrder(matrix) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"test('3 × 3', () => {\n  expect(spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]])).toEqual([1, 2, 3, 6, 9, 8, 7, 4, 5]);\n});\n\ntest('3 × 4 (wider than tall)', () => {\n  expect(spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])).toEqual([1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]);\n});\n\ntest('4 × 2 (taller than wide)', () => {\n  expect(spiralOrder([[1, 2], [3, 4], [5, 6], [7, 8]])).toEqual([1, 2, 4, 6, 8, 7, 5, 3]);\n});\n\ntest('single row and single column', () => {\n  expect(spiralOrder([[1, 2, 3]])).toEqual([1, 2, 3]);\n  expect(spiralOrder([[1], [2], [3]])).toEqual([1, 2, 3]);\n  expect(spiralOrder([[42]])).toEqual([42]);\n});\n\ntest('empty matrices', () => {\n  expect(spiralOrder([])).toEqual([]);\n  expect(spiralOrder([[]])).toEqual([]);\n});\n\ntest('5 × 3 with a single middle column left', () => {\n  const m = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]];\n  expect(spiralOrder(m)).toEqual([1, 2, 3, 6, 9, 12, 15, 14, 13, 10, 7, 4, 5, 8, 11]);\n});\n\ntest('performance: 500 × 500', () => {\n  const n = 500;\n  const m = Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => r * n + c));\n  const got = spiralOrder(m);\n  expect(got).toHaveLength(n * n);\n  expect(got.slice(0, 3)).toEqual([0, 1, 2]);\n  expect(got[n]).toBe(2 * n - 1);\n  expect(got[n * n - 1]).toBe(250 * n + 249);\n  expect(got.reduce((a, b) => a + b, 0)).toBe(((n * n - 1) * n * n) / 2);\n});\n"},{"lang":"python","runner":"browser","starter":"def spiral_order(matrix: list[list[int]]) -> list[int]:\n    \"\"\"Returns all elements of the matrix in clockwise spiral order.\"\"\"\n    raise NotImplementedError\n","testCount":7,"tests":"def check(matrix, expected):\n    got = spiral_order(matrix)\n    assert got == expected, f\"spiral_order({matrix}): expected {expected}, got {got}\"\n\n\ndef test_3x3():\n    check([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [1, 2, 3, 6, 9, 8, 7, 4, 5])\n\n\ndef test_3x4_wider_than_tall():\n    check([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7])\n\n\ndef test_4x2_taller_than_wide():\n    check([[1, 2], [3, 4], [5, 6], [7, 8]], [1, 2, 4, 6, 8, 7, 5, 3])\n\n\ndef test_single_row_and_single_column():\n    check([[1, 2, 3]], [1, 2, 3])\n    check([[1], [2], [3]], [1, 2, 3])\n    check([[42]], [42])\n\n\ndef test_empty_matrices():\n    check([], [])\n    check([[]], [])\n\n\ndef test_5x3_single_middle_column_left():\n    m = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]\n    check(m, [1, 2, 3, 6, 9, 12, 15, 14, 13, 10, 7, 4, 5, 8, 11])\n\n\ndef test_performance_500x500():\n    n = 500\n    m = [[r * n + c for c in range(n)] for r in range(n)]\n    got = spiral_order(m)\n    assert len(got) == n * n, f\"expected {n * n} values, got {len(got)}\"\n    assert got[:3] == [0, 1, 2], f\"first values: {got[:3]}\"\n    assert got[n] == 2 * n - 1, f\"value after the first row: {got[n]}\"\n    assert got[-1] == 250 * n + 249, f\"last value: {got[-1]}\"\n    assert sum(got) == (n * n - 1) * n * n // 2, \"every element exactly once\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\npublic static class Solution\n{\n    /// <summary>Returns all elements of the matrix in clockwise spiral order.</summary>\n    public static List<int> SpiralOrder(int[][] matrix)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":7},{"lang":"java","runner":"judge0","starter":"import java.util.*;\n\nclass Solution {\n    /** Returns all elements of the matrix in clockwise spiral order. */\n    static List<Integer> spiralOrder(int[][] matrix) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":7},{"lang":"go","runner":"judge0","starter":"package main\n\n// SpiralOrder returns all elements of the matrix in clockwise spiral order.\nfunc SpiralOrder(matrix [][]int) []int {\n\tpanic(\"not implemented\")\n}\n","testCount":7}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.774Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"An LED display draws a \"snail\" animation: it lights LEDs from the top-left corner along the edges, clockwise and closer to the centre with every lap. We need the order of values for any rectangular "},{"type":"text","text":"m × n","marks":[{"type":"code"}]},{"type":"text","text":" matrix."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"Return all elements of the matrix in spiral order: the first row to the right, the last column down, the last row to the left, the first column up – and so on for the inner \"rings\". Every element appears "},{"type":"text","text":"exactly once","marks":[{"type":"bold"}]},{"type":"text","text":"."}]},{"type":"paragraph","content":[{"type":"text","text":"Signatures: "},{"type":"text","text":"spiralOrder(matrix)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"spiral_order(matrix)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.SpiralOrder","marks":[{"type":"code"}]},{"type":"text","text":" (C#, "},{"type":"text","text":"int[][]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"Solution.spiralOrder","marks":[{"type":"code"}]},{"type":"text","text":" (Java, "},{"type":"text","text":"int[][]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"SpiralOrder","marks":[{"type":"code"}]},{"type":"text","text":" (Go)."}]},{"type":"heading","attrs":{"level":2,"id":"examples"},"content":[{"type":"text","text":"Examples"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Matrix"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[1,2,3],[4,5,6],[7,8,9]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[1,2,3,6,9,8,7,4,5]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[1,2,3,4],[5,6,7,8],[9,10,11,12]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[1,2,3,4,8,12,11,10,9,5,6,7]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[1],[2],[3]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[1,2,3]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":" or "},{"type":"text","text":"[[]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"0 ≤ m, n ≤ 500","marks":[{"type":"code"}]},{"type":"text","text":", all rows have the same length."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(m · n)","marks":[{"type":"bold"}]},{"type":"text","text":" time, "},{"type":"text","text":"O(1)","marks":[{"type":"bold"}]},{"type":"text","text":" extra memory besides the result."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/spiral-matrix/","title":"LeetCode 54 – Spiral Matrix","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:55.776Z","updatedAt":"2026-11-27T08:22:55.776Z"}