A2Z Lesson

Log in
← Back to the A2Z sheet

Step 01 Beginner Problems — Patterns

Pattern 22 — Number Pattern

Medium

A square of numbers arranged in concentric layers like an onion: the outermost ring is all n, the next ring in is n - 1, and the value drops by one per layer until the single center cell holds 1. For n = 4 the square is 7x7, and the figure reads identically along every row, column, and line of symmetry.

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
Output for n = 4

How to think about it

The grid has size 2n - 1 (so there is a single center cell). For the cell at (i, j), compute its distance to the nearest edge: dist = min(i, j, size - 1 - i, size - 1 - j). Edge cells have dist 0, the next ring dist 1, and the center dist n - 1. The printed value is n - dist. That is the whole pattern — no row or column formula, just 'how deep is this cell?'. Every ring of constant dist is a square frame of the kind Pattern 21 draws, and the frames nest inside each other.

Code

Two nested loops walk the (2n - 1) x (2n - 1) grid. For each cell the code takes the minimum of the four distances to the edges and prints n minus that distance. The min-of-four-distances idiom is the entire algorithm — everything else is the standard grid-printing skeleton from Pattern 1.

def pattern(n): size = 2 * n - 1 for i in range(size): row = [] for j in range(size): dist = min(i, j, size - 1 - i, size - 1 - j) row.append(str(n - dist)) print(" ".join(row))

Key points

  • Grid size is 2n - 1, not n — the input counts layers, and layers need a center.
  • Cell value = n - min(i, j, size-1-i, size-1-j): distance to the nearest edge decides everything.
  • Each constant-value ring is a hollow square — Pattern 21 nested inside itself.
  • The center cell is always 1 and the border is always n — instant sanity checks.
  • The figure has four-way symmetry: rows read the same as columns.

Suggested questions

Pattern 21 — Hollow Rectangle Pattern One hollow frame; this pattern nests that frame inside itself n times.
Pattern 12 — Number Crown Pattern Another figure where a cell's value comes from its position rather than a counter.
Pattern 19 — Symmetric-Void Pattern Two blocks and a void on a fixed canvas — positional thinking like the ring distance.
GCD of Two Numbers ↗ Built on min/max reasoning about pairs of numbers — the same comparison habit as min-of-four-distances.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.