← Accenture bank

Accenture · Question 11 · Arrays

Spiral Matrix

ArraysC++code⏱ O(m×n)💾 O(m×n)
Service-based

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

  1. 1Walk right, down, left, up around the rim.
  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(m×n)Space O(m×n)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>using namespace stdvector<int>spiralOrder(vector<vector<int>>&matrix)DEFINE printVec(constvector<int>& v)cout << "["for (size_t i = 0; i <v.size(); ++i)if (i) cout << ", "cout << v[i]cout << "]" << endlDEFINE main()vector<vector<int>> matrix= {{1, 2, 3}, {4, 5, 6},{7, 8, 9}}printVec(spiralOrder(matrix))RETURN 0END
  • 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