Generate a Spiral Matrix
Updated
Problem statement
Given a positive integer n, create an n by n matrix containing the integers from 1 through n * n in clockwise spiral order.
Begin with 1 in the top-left cell and initially move right.
Function
generateMatrix(n: int) → int[][]Examples
Example 1
n = 3return = [[1,2,3],[8,9,4],[7,6,5]]The values wrap clockwise around the boundary before filling the center cell.
Example 2
n = 1return = [[1]]A one-cell matrix contains only 1.
Constraints
nis positive.n * nfits in a signed integer.
More Microsoft Onsite Interview questions
- Bad Request AlertsONSITE INTERVIEW · Seen Nov 2026
- Longest Substring Without Repeating CharactersONSITE INTERVIEW · Seen Nov 2026
- Valid ParenthesesONSITE INTERVIEW · Seen Nov 2026
- Count a User's Actions in an Event LogONSITE INTERVIEW · Seen Nov 2026
- Smallest Batch Size Within a Step LimitONSITE INTERVIEW · Seen Nov 2026
- Count Subarrays with Equal Even and Odd CountsONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Rot All OrangesONSITE INTERVIEW · Seen Nov 2026
- Coin ChangeONSITE INTERVIEW · Seen Oct 2026
- Daily USD Totals with Effective-Dated Exchange RatesONSITE INTERVIEW · Seen Oct 2026
- Number Words to Digits in Any LanguageONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Random Bingo Card GeneratorUber · ONSITE INTERVIEWUber interview questions
- Rectangle Point Coverage CountsOpenAI · PHONE SCREEN · ONSITE INTERVIEWOpenAI interview questions
- Spiral MatrixAthenahealth · ONSITE INTERVIEW
- Explore an Unknown Grid and Find a PathLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Spiral MatrixNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Tic-Tac-Toe Move WinnersByteDance · ONSITE INTERVIEWByteDance interview questions
- Trace Every Water Drop to Its Resting DestinationGoogle · ONSITE INTERVIEWGoogle interview questions
- Stochastic Gradient Descent with MomentumMeta · ONSITE INTERVIEWMeta interview questions
- Cyclic Fuel Command SimulationWaymo · ONSITE INTERVIEWWaymo interview questions
- Spiral Matrix with ObstaclesTemu · ONSITE INTERVIEWTemu interview questions
Microsoft interview experiences
- Microsoft OA Questions, October 2026: 4 Experiences
- Microsoft Experienced SWE Phone Screen: 1 Experience
- Microsoft Explore and Student SWE: 12 Experiences (Part 6 of 6)
- Microsoft SWE Intern, Early 2025: 41 Experiences (Part 5 of 6)
- Microsoft SWE Intern, Mid 2025: 42 Experiences (Part 4 of 6)
- Microsoft SWE Intern, Late 2025: 47 Experiences (Part 3 of 6)