Print a Number Increasing Reverse Pyramid

Solve this Problem
Easy10 min
Topics
Companies
Given an integer n, return the n rows of an upside-down centered number pyramid — row i has (i − 1) leading spaces, followed by the numbers 1 through (n − i + 1). This is the Number Increasing Pyramid, flipped: the widest row (1 through n, no spaces) comes first, narrowing by one number — and gaining one leading space — each row after. Both solutions carry over the Number Increasing Pyramid's technique directly, just with (i − 1) and (n − i + 1) swapped in for the space and number counts.

Test Case 1:

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

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 (i − 1) spaces, then append the numbers 1 through (n − i + 1). The upside-down version of the Number Increasing Pyramid: the widest row (1 through n, no spaces) comes first, narrowing by one number — and gaining one leading space — each row after.

TimeO(n²)
SpaceO(n²) for the output
1class Solution { 2 public String[] printNumberIncreasingReversePyramid(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 <= i - 1; s++) { 7 row.append(' '); 8 } 9 for (int j = 1; j <= n - i + 1; 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. C has neither built-in, so it keeps both loops.

TimeO(n²)
SpaceO(n²)
1class Solution { 2 public String[] printNumberIncreasingReversePyramid(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 String spaces = " ".repeat(i - 1); 6 String nums = java.util.stream.IntStream.rangeClosed(1, n - i + 1) 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