Accenture · Question 11 · Arrays
Spiral Matrix
Problem
Return all elements of the matrix in spiral order.
Approach
Traverse the matrix layer by layer — moving right, down, left, and up — adjusting boundaries after each pass.
Time O(m×n)Space O(m×n)
How it works
- 1Walk right, down, left, up around the rim.
- 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(m×n)Space O(m×n)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/15
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