Print a Number Changing Pyramid

Solve this Problem
Easy10–15 min
Topics
Companies
Given an integer n, return the n rows of a "changing" number pyramid — row i counts up from 1 to i, then back down to 1. The nested loopsNested LoopsAn ascending inner loop (1 to i) followed immediately by a descending one (i-1 down to 1), each with their own space-handling. version writes the direction change as two separate loops back to back. The two rangesBuild Two Ranges, Then JoinGenerating the ascending and descending sequences as two separate lists, concatenating them, then joining the combined result once. version builds the same two pieces as data first, concatenates them, and joins ONLY once — so there's no risk of mismatched space logic where the two directions meet.

Test Case 1:

Input:n = 3
Output:["1", "1 2 1", "1 2 3 2 1"]
Explanation:Row i counts up from 1 to i, then back down to 1.

Test Case 2:

Input:n = 1
Output:["1"]
Explanation:A single row — up to 1, with nothing to count back down from.

Constraints

  • ◆1 ≤ n ≤ 9

Try the Dry Run

Approach & Solutions

Nested Loops — Up, Then DownGood

For row i, first run an ascending inner loop from 1 to i (exactly the Increasing Number Triangle's row), then run a second, descending inner loop from i − 1 back down to 1 — the "direction change" is literally two back-to-back loops.

TimeO(n²)
SpaceO(n²) for the output
1class Solution { 2 public String[] printNumberChangingPyramid(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 StringBuilder row = new StringBuilder(); 6 for (int j = 1; j <= i; j++) { 7 if (j > 1) row.append(' '); 8 row.append(j); 9 } 10 for (int j = i - 1; j >= 1; j--) { 11 row.append(' '); 12 row.append(j); 13 } 14 result[i - 1] = row.toString(); 15 } 16 return result; 17 } 18}
Build Two Ranges, Then JoinOptimal

Build the ascending part (1 to i) and the descending part (i − 1 down to 1) as two separate sequences, concatenate them, and join the result — the "direction change" becomes concatenating two ranges instead of writing two separate loops with their own space-handling logic.

TimeO(n²)
SpaceO(n²)
1class Solution { 2 public String[] printNumberChangingPyramid(int n) { 3 String[] result = new String[n]; 4 for (int i = 1; i <= n; i++) { 5 List<Integer> nums = new ArrayList<>(); 6 for (int j = 1; j <= i; j++) nums.add(j); 7 for (int j = i - 1; j >= 1; j--) nums.add(j); 8 result[i - 1] = nums.stream().map(String::valueOf).collect(Collectors.joining(" ")); 9 } 10 return result; 11 } 12}

Related Problems