PPractick

DSA interview question

Pattern 22: Concentric Number Square

Medium · Algorithms · Topics: pattern building

The problem

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

Function signature

vector<string> concentricSquare(int n);  // (2n - 1) rows of (2n - 1) space-separated numbers

Test cases

Input nOutput rowsExplanation
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
4as in the example7 × 7 grid

(Confirm: numbers are space-separated with no trailing space; the grid side is 2n − 1.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the grid size 2n − 1?
  2. Space-separated?
  3. Print or return?

Follow-ups to expect

  1. "How do you compute a cell without drawing rings?"
  2. "Why the minimum of four distances?"
  3. "How would you print the rings in reverse (1 on the outside)?"
  4. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in