Print a Reverse Number Triangle
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of an upside-down number triangle — row i counts down from (n − i + 1) to 1.
This mirrors the Reverse Right Half Pyramid's shrinking row lengths, filled with counting-down numbers instead of stars. The nested loopsNested LoopsAn outer loop over rows, an inner loop counting down from len to 1 for each row. version builds each row number by number. The range + joinRange + JoinGenerating the descending range len down to 1 directly, then joining it with spaces. version generates the same descending sequence as a single range-and-join expression.
Test Case 1:
Input:n = 3
Output:["3 2 1", "2 1", "1"]
Explanation:Row i counts down from (n − i + 1) to 1.
Test Case 2:
Input:n = 1
Output:["1"]
Explanation:A single row, just "1".
Constraints
- ◆
1 ≤ n ≤ 9
Try the Dry Run
Approach & Solutions
Nested Loops — Count Down Each RowGood
For row i, compute len = n − i + 1 — the row's length shrinks exactly like the Reverse Right Half Pyramid's star count — then run an inner loop counting DOWN from len to 1, appending each number.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printReverseNumberTriangle(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 int len = n - i + 1;
6 StringBuilder row = new StringBuilder();
7 for (int j = len; j >= 1; j--) {
8 if (j < len) row.append(' ');
9 row.append(j);
10 }
11 result[i - 1] = row.toString();
12 }
13 return result;
14 }
15}Build with Range + JoinOptimal
Row i is just the numbers len down to 1 (where len = n − i + 1) — generate that descending range directly and join it. C has no such built-in, so it keeps the explicit loop.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printReverseNumberTriangle(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 int len = n - i + 1;
6 result[i - 1] = java.util.stream.IntStream.rangeClosed(1, len)
7 .map(k -> len - k + 1)
8 .mapToObj(String::valueOf)
9 .collect(java.util.stream.Collectors.joining(" "));
10 }
11 return result;
12 }
13}