Print a Palindrome Number Pyramid

Solve this Problem
Easy10 min
Topics
Companies
Given n (at most 9, so every number is a single digit), return n centred rows where row i counts up from 1 to i and back down to 1 — for example "12321" for i = 3. Every row is a palindromePalindromeA sequence that reads the same forwards and backwards, such as 12321., and the rows grow by two characters each time, which is why they stack into a pyramid once n − i leading spaces are added. The second solution uses the palindrome property directly: build the rising half once and mirror it.

Test Case 1:

Input:n = 4
Output:[" 1", " 121", " 12321", "1234321"]
Explanation:Row i counts up from 1 to i and back down, so it reads the same in both directions.

Test Case 2:

Input:n = 1
Output:["1"]
Explanation:The single row is just "1".

Constraints

  • ◆1 ≤ n ≤ 9

Try the Dry Run

Approach & Solutions

Nested Loops — Count Up, Then DownGood

Row i has n − i leading spaces, then the digits 1, 2, …, i, then i − 1, …, 1. Three inner loops write the spaces, the rising digits and the falling digits. The peak digit i appears once.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printPalindromePyramid(int n) { String[] result = new String[n]; for (int i = 1; i <= n; i++) { StringBuilder row = new StringBuilder(); for (int s = 0; s < n - i; s++) { row.append(' '); } for (int j = 1; j <= i; j++) { row.append(j); } for (int j = i - 1; j >= 1; j--) { row.append(j); } result[i - 1] = row.toString(); } return result; } }
Mirror the Rising HalfOptimal

Keep a growing string of rising digits: "1", "12", "123", … Each row is that string followed by its own reverse without the last digit. C writes each digit j into both mirrored positions of the row at once.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printPalindromePyramid(int n) { String[] result = new String[n]; StringBuilder left = new StringBuilder(); for (int i = 1; i <= n; i++) { left.append(i); String right = new StringBuilder(left.substring(0, i - 1)).reverse().toString(); result[i - 1] = " ".repeat(n - i) + left + right; } return result; } }

Related Problems