VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-given-matrix-reverse-spiral-form/

⇱ Print a given matrix in reverse spiral form - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print a given matrix in reverse spiral form

Last Updated : 28 May, 2026

Given an n × m matrix, return its elements in reversespiral order. 

Note: Reverse spiral order starts from the center of the matrix (or the closest valid center for even dimensions) and moves outward in a spiral.

Examples:

Input: n = 3, m = 3

👁 blobid0_1779802052

Output: [5, 6, 3, 2, 1, 4, 7, 8, 9]
Explanation: Spiral form of the matrix in reverse order starts from the centre and goes outward.

👁 blobid0_1779806437


Input: n = 4, m = 4

👁 blobid2_1779802154

Output: [10, 11, 7, 6, 5, 9, 13, 14, 15, 16, 12, 8, 4, 3, 2, 1]
Explanation: Spiral form of the matrix in reverse order starts from the centre and goes outward.

👁 blobid4_1779802234

[Naive Approach] Generate Spiral Traversal and Reverse It - O(n * m) Time O(n * m) Space

The idea is to first traverse the matrix in normal spiral order and store all elements in a vector. Since reverse spiral order is exactly the reverse of normal spiral traversal, reverse the stored vector and return it as the answer.


Output
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 

Time Complexity: O(n * m)
AuxiliarySpace: O(n * m)

[Expected Approach] Boundary Traversal with Final Reversal - O(n * m) Time O(1) Space

The idea is to use four boundaries (top, bottom, left, right) to traverse the matrix layer by layer in spiral order. Store the traversal in a vector and reverse the vector at the end to get the reverse spiral order starting from the center and moving outward.


Output
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 

Time Complexity: O(n * m)
AuxiliarySpace: O(1)

Comment