Home › Company-wise questions › Deloitte › Spiral Matrix ← Deloitte bank
Deloitte · Question 33
Spiral Matrix Java code ⏱ O(mn) 💾 O(1)
Service-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Traverse a matrix in spiral order, shrinking boundaries each loop.
Approach Walk right, down, left, up, tightening top/bottom/left/right.
Time O(mn)Space O(1)
How it works 1 Walk the rim right, down, left, up. 2 Shrink the boundaries after each side. Sample input / output Input:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output:
[1, 2, 3, 6, 9, 8, 7, 4, 5] Constraints 1 <= m, n <= 10.
Solution — read it, then walk it Flowchart Pseudocode
Time O(mn)Space O(1)Loops 5Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no yes ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static List<Integer> spiralOrder(int[][] matrix) List<Integer> res = new ArrayList<>() if (matrix.length == 0) return res DEFINE top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].lengt… while (top <= bottom && left <= right) for (int j = left; j <= right; j++) res.add(matrix[top][j]) top++ for (int i = top; i <= bottom; i++) res.add(matrix[i][right]) right-- if (top <= bottom) for (int j = right; j >= left; j--) res.add(matrix[bottom][j]) bottom-- if (left <= right) for (int i = bottom; i >= top; i--) res.add(matrix[i][left]) left++ RETURN res DEFINE static void main(String[] args) System.out.println(spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}})) END start / end statement condition loop returns definition← Q32 · Set Matrix Zeroes Q34 · Rotate Array → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →