Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Read a grid in a clockwise spiral

    MediumAbout 25 minFull AccessLearn it: Arrays and Strings in C#: Prefix Sums, Kadane, In-Place Rotation and Counting Arrays

    The task

    A warehouse display shows the readings of a rectangular block of sensors as one scrolling line, read in a clockwise spiral from the outside in.

    Complete SpiralOrder(int[][] matrix). Return the values in clockwise spiral order. Start at the top-left corner and go right along the top row, down the right column, left along the bottom row and up the left column. Then do the same with the smaller rectangle inside, until every value has been read exactly once. All rows have the same length. A matrix with no rows, or with empty rows, gives an empty list. The matrix is never null.

    Signature

    public static List<int> SpiralOrder(int[][] matrix)

    Examples

    • [[1, 2], [3, 4]] → [1, 2, 4, 3]. Right along the top, down the right column, then left along the bottom.
    • [[21, 22, 23], [24, 25, 26], [27, 28, 29]] → [21, 22, 23, 26, 29, 28, 27, 24, 25]. The outer ring first, then the middle value.

    Limits: Up to 500 rows and 500 columns.

    The tests check: a matrix with no rows, empty rows, one value, one row, one column, rectangles wider than tall and taller than wide, and a 50 × 37 grid read once each, in order.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // Returns the values of the matrix in clockwise spiral order, from the top-left corner inward.
          public static List<int> SpiralOrder(int[][] matrix)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.