In this problem our objective is to take in a two dimensional array and traverse it in a spiral manner and return a one-dimensional array of all the array’s element in spiral order.
This problem is popular in coding interview because it test how well a candidate can transcribe simple login into code.
This problem can be solved recursively or iteratively.
We can essentially traverse through the outer perimeter of the 2d array and traverse through the inner perimeter.
Solution
To solve this we can create some variables to indicate the sR (starting row) eR (ending row) and sC (starting column) and eC (ending column).
We start at the starting row and begin traversing and adding to the final array. Starting off at 1 we can move on to the next value which is 2. moving the index as we go.
Essentially in this solution we are using pointers and a starting and ending for columns and rows. Once we’ve iterated over the outer perimeter then we move the dimension inwards by one.
Once sR has crossed eR and sC has crossed eC then we know that we don’t need to iterate anymore.
Time Complexity: O(N) , we are traversing the entire array. Space Complexity: O(N) , since we are storing n values in a new array.