Print Matrix In Spiral Order Problem

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<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 --------
</vector

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary