Interview Questions

  • View all interview questions
  • blank
  • Print a matrix in spiral order
    The input for this problem will be a matrix, or multidimensional array, which will be represented by N arrays each of N length, and your goal is to print the matrix in a spiral order. For example, if the input is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] then this matrix should be printed out in a list like so: [1, 2, 3, 6, 9, 8, 7, 4, 5] The spiral begins at the top left of the matrix and loops around it towards the center in a clockwise pattern. Below is a clever algorithm that uses recursion to print a matrix in spiral order:


    You need to be a premium member to see the rest of this question and code.

    Become a Premium Member

    With our large collection of challengs, tutorials, and solutions, we make it easy for you to become a better coder, prepare for interviews, and learn new skills from more experienced coders.

    “Also important to try coding in nonstructured or semistructured environments to see if you like it. Coderbyte really helped me.“ ― Jeff Ruder
    • 200+ Coding Challenges
    • Mock Interview Questions
    • 500,000+ Code Solutions
    • Algorithm Tutorials
    • Interview Prep Courses
    mrdaniel published this on 11/12/15 | array, matrix, Microsoft
  • +
  • 2
  • -
  • I tried this way.........
    function spiral(matrix){
      var list= [];
        list= list.concat(matrix.splice(0,1)[0]);
        for(var idx in matrix){
        list= list.concat(matrix.splice(-1,1)[0].reverse());
        for(var idx=matrix.length-1;idx>=0;idx--){
      return list;
    // setup a matrix
    var M = [[1, 2, 3], 
             [4, 5, 6], 
             [7, 8, 9]];
    // return it in spiral order
    Login to submit a comment