← Deloitte bank

Deloitte · Question 33

Spiral Matrix

Javacode⏱ O(mn)💾 O(1)
Service-based

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. 1Walk the rim right, down, left, up.
  2. 2Shrink 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

Time O(mn)Space O(1)Loops 5Branches 3Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesnoyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static List<Integer>spiralOrder(int[][] matrix)List<Integer> res = newArrayList<>()if (matrix.length ==0) return resDEFINE 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 resDEFINE static voidmain(String[] args)System.out.println(spiralOrder(newint[][]{{1, 2, 3}, {4, 5,6}, {7, 8, 9}}))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits