DSA interview question
The last pattern in the series prints a (2n − 1) × (2n − 1) square of numbers made of concentric rings: the outermost ring is all n, the next ring inside is n − 1, and so on down to a single 1 in the centre. Building it ring by ring is awkward. The elegant solution computes each cell directly: its value depends on how far the cell is from the nearest edge. That "distance to the nearest boundary" idea shows up again in matrix and BFS problems.
Example for n = 4:
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
vector<string> concentricSquare(int n); // (2n - 1) rows of (2n - 1) space-separated numbers
Input n | Output rows | Explanation |
|---|---|---|
| 1 | "1" | A 1 × 1 grid |
| 2 | "2 2 2", "2 1 2", "2 2 2" | Ring of 2s around a 1 |
| 3 | "3 3 3 3 3", "3 2 2 2 3", "3 2 1 2 3", "3 2 2 2 3", "3 3 3 3 3" | Three rings |
| 4 | as in the example | 7 × 7 grid |
(Confirm: numbers are space-separated with no trailing space; the grid side is 2n − 1.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in