Log In

SkillUpper

Practice coding interview questions step-by-step
Coding interview questions can be hard to figure out on your own
Traverse a matrix in a spiral
What if you cannot come up with a solution to that problem?
You could look up the answer to a question you don't know,
but it's hard to get a detailed understanding that way
What if you got a hint on how to start a solution?
Traverse the outer layer of the matrix
That subproblem is easier to solve first,
and then you can work on next steps
Traverse the outer two layers
Traverse the whole matrix in a spiral
These guided step-by-step tutorials allow you to solve these problems yourself, while getting hints on the right path to take

We would like to write a function that traverses a square matrix in a spiral. The spiral would go from outside to inside, and would go in clockwise order.

For example, given this input:
ABCD
EFGH
IJKL
MNOP

The output of the function would be:
["A","B","C","D","H","L","P","O","N","M","I","E","F","G","K","J"]


However, let's take this step by step. First, let's write a function called that would traverse the outer layer of the matrix.

For this input:
ABCD
EFGH
IJKL
MNOP

The output of the function would be:
["A","B","C","D","H","L","P","O","N","M","I","E"]

This can be implemented with 4 loops for the 4 edges of the matrix to traverse.

Sign Up or Log In to access the code editor and answer the question!
Log In

Other tutorials:
N Queens - Recursive Backtracking
Fibonacci - Dynamic Programming
Basketball Scores - Dynamic Programming