About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Print Matrix In Spiral Order Problem

Given a character matrix, return all the characters in the clockwise spiral order starting from the top-left.

Example

Input:

[

['X' 'Y' 'A']

['M' 'B' 'C']

['P' 'Q' 'R']

]

Output: "XYACRQPMB"

For the given matrix rows = 3 and cols = 3. Spiral order is 'X' -> 'Y' -> 'A' -> 'C' -> 'R' -> 'Q' -> 'P' -> 'M' -> 'B'. So return string "XYACRQPMB" of length rows * cols = 9.

Notes

Input Parameters: There is only one argument denoting character matrix matrix.

Output: Return a string res, of length rows * cols denoting the spiral order of matrix.

Constraints:

  • 1 <= rows, cols
  • 1 <= rows * cols <= 10^5
  • Any character in matrix will be either uppercase letter ('A' - 'Z') or lowercase letter ('a' - 'z').
  • Avoid recursion.

 This problem is less about logic, but more about careful index manipulation.

Hint - It may be faster to write this, if you name your variables clearly. Instead of i,j,k,l etc, try naming them like row, col, start, end etc. That will also help your interviewer follow along more easily.

Solution

There are many solutions possible for this problem.

Here we will provide one interesting solution that uses only one for loop. Suppose we start from the top-left corner (0, 0) and turn right at certain locations (indicated by # signs). Then we will visit the matrix in spiral order.

For a 4 * 4 grid (even * even):

O O O O

O O O O

O O O O

O O O O

The signs will be like this:

O O O #

# O # O

O # # O

# O O #

For a 4 * 5 grid (even * odd):

O O O O O

O O O O O

O O O O O

O O O O O

The signs will be like this:

O O O O #

# O O # O

O # O # O

# O O O #

For a 5 * 4 grid (odd * even):

O O O O

O O O O

O O O O

O O O O

O O O O

The signs will be like this:

O O O #

# O # O

O # O O

O # # O

# O O #

For a 5 * 5 grid (odd * odd):

O O O O O

O O O O O

O O O O O

O O O O O

O O O O O

The signs will be like this:

O O O O #

# O O # O

O # # O O

O # O # O

# O O O #

We can divide the grid in 4 parts and then follow some patterns.

4 parts will be:

1) top-left (lets call it a)

2) top-right (lets call it b)

3) bottom-right (lets call it c)

4) bottom-left (lets call it d)

So 6 * 6 grid will be divided like:

a a a b b b

a a a b b b

a a a b b b

d d d c c c

d d d c c c

d d d c c c

Now for most of the points we can easily decide in which part they will fall, except points which are horizontally centered or vertically centered. Horizontally centered points: Consider them in top parts. Vertically centered points: Consider them in right parts.

So 5 * 7 grid will be divided like:

a a a b b b b

a a a b b b b

a a a b b b b

d d d c c c c

d d d c c c c

Now again look at the grid:

O O O O O O #

# O O O O # O

O # O O # O O

O # O O O # O

# O O O O O #

and try to find patterns from parts:

O O O  O O O #

# O O   O O # O

O # O   O # O O

O # O   O O # O

# O O   O O O #

For top-right, bottom-right and bottom-left pattern is same!

If matrix size is rows * cols then for any point (at position cur_row and cur_col) if we want to check if there is a sign or not simply check:

1) top-right: cur_row == cols - 1 - cur_col

2) bottom-right: rows - 1 - cur_row == cols - 1 - cur_col

3) bottom-left: rows - 1 - cur_row == cur_col

We can write conditions separately or combine them as:

min(cur_row, rows - 1 - cur_row) == min(cur_col, cols - 1 - cur_col) ......(1)

Now for the top-left part we need to check:

cur_row == cur_col + 1 ......(2)

Now you know where to put the signs! How to check if point is in top-left or other parts?

/*

Consider these grids to understand what the below code does.

O O O O O O #

# O O O O # O

O # O O # O O

O # O O O # O

# O O O O O #

=

O O O  O O O #

# O O   O O # O

O # O   O # O O

 

O # O   O O # O

# O O   O O O #

< (rows + 1) / 2 will give priority to top part when current position is horizontally centered.

< cols / 2 will give priority to right part when current position is vertically centered.

*/

if ((cur_row < (rows + 1) / 2) && (cur_col < cols / 2))

{

     // Condition to turn when current position is in top-left part.

}

else

{

     // Condition to turn when current position in other parts.

}

Time Complexity:

O(rows * cols).

We are traversing the whole vector once.

Auxiliary Space Used:

O(1).

Space Complexity:

O(rows * cols).


// -------- START --------

int directions[4][2] = 
{
	// {row, col}
	{0, 1}, 	// go right 
	{1, 0}, 	// go down
	{0, -1}, 	// go left 
	{-1, 0} 	// go up.
};

bool should_turn(int cur_row, int cur_col, int rows, int cols)
{
	/*
	Consider these grids to understand what the below code does. 
	O O O O O O #
	# O O O O # O
	O # O O # O O
	O # O O O # O
	# O O O O O #
	=
	O O O	 O O O #
	# O O	 O O # O
	O # O	 O # O O
	O # O	 O O # O
	# O O	 O O O #
	< (rows + 1) / 2 will give priority to top part when current position is horizontally 
	centered. 
	< cols / 2 will give priority to right part when current position is vertically centered.
	
	*/

	// Check if position is in top-left part.
	if ((cur_row < (rows + 1) / 2) && (cur_col < cols / 2))
	{
		// Condition to turn when current position is in top-left part.
		return cur_row == cur_col + 1;
	}
	// Condition to turn when current position in other parts.
	return min(cur_row, rows - 1 - cur_row) == min(cur_col, cols - 1 - cur_col);
}

string printSpirally(vector> matrix)
{
	int rows = matrix.size();
	int cols = matrix[0].size();
	int total = rows * cols;
	string ans(total, ' ');
	// Initial position is at top left corner with direction towards right. 
	int direction = 0;
	int cur_row = 0, cur_col = 0;
	for (int i = 0; i < total; i++)
	{
		ans[i] = matrix[cur_row][cur_col];
		// Check if we should turn our direction or not.
		if (should_turn(cur_row, cur_col, rows, cols))
		{
			direction = (direction + 1) % 4;
		}
		// Update the position.
		cur_row += directions[direction][0];
		cur_col += directions[direction][1];
	}
	return ans;
}

// -------- END --------