Print a Number Increasing Pyramid

Solve this Problem
Easy10 min
Topics
Companies
Given an integer n, return the n rows of a centered number pyramid — row i has (n − i) leading spaces, followed by the numbers 1 through i. This borrows the Left Half Pyramid's exact space formula, filled with counting numbers instead of stars. The nested loopsNested LoopsAn outer loop over rows, one inner loop for the leading spaces, another for the numbers. version builds each piece explicitly; the built-in repeat + range/joinBuilt-in Repeat + Range/JoinBuilding the spaces with a repeat and the numbers with a range-and-join, then concatenating the two pieces. version replaces both inner loops with two built-in calls and a concatenation.

Test Case 1:

Input:n = 3
Output:[" 1", " 1 2", "1 2 3"]
Explanation:Row i has (n − i) leading spaces, then the numbers 1 through i — a centered pyramid shape.

Test Case 2:

Input:n = 1
Output:["1"]
Explanation:A single row, no spaces needed.

Constraints

  • ◆1 ≤ n ≤ 9

Try the Dry Run

Approach & Solutions

Nested Loops — Spaces, Then NumbersGood

For row i, first append (n − i) spaces, then append the numbers 1 through i — the Left Half Pyramid's exact space formula, filled with counting numbers instead of stars.

TimeO(n²)
SpaceO(n²) for the output
1class Solution { 2 public String[] printNumberIncreasingPyramid(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 StringBuilder row = new StringBuilder(); 6 for (int s = 1; s <= n - i; s++) { 7 row.append(' '); 8 } 9 for (int j = 1; j <= i; j++) { 10 if (j > 1) row.append(' '); 11 row.append(j); 12 } 13 result[i - 1] = row.toString(); 14 } 15 return result; 16 } 17}
Built-in Repeat for Spaces, Range + Join for NumbersOptimal

Build the leading spaces with a repeat, and the numbers with a range-and-join, then concatenate the two pieces — no inner loop written by hand for either half. C has neither built-in, so it keeps both loops.

TimeO(n²)
SpaceO(n²)
1class Solution { 2 public String[] printNumberIncreasingPyramid(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 String spaces = " ".repeat(n - i); 6 String nums = java.util.stream.IntStream.rangeClosed(1, i) 7 .mapToObj(String::valueOf) 8 .collect(java.util.stream.Collectors.joining(" ")); 9 result[i - 1] = spaces + nums; 10 } 11 return result; 12 } 13}

Related Problems