Print an Increasing Number Triangle
Solve this ProblemEasy5–10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of a number triangle — row i counts from 1 up to i, space-separated.
This is the Right Half Pyramid's shape, filled with counting numbers instead of stars. The nested loopsNested LoopsAn outer loop over rows, an inner loop counting from 1 to i and appending each number. version builds each row number by number. The range + joinRange + JoinGenerating the range 1 to i directly, then joining it with spaces — no manual index or space bookkeeping. version describes the same row as a single range-and-join expression.
Test Case 1:
Input:n = 3
Output:["1", "1 2", "1 2 3"]
Explanation:Row i counts up from 1 to i.
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 — Print Each NumberGood
For row i, run an inner loop from 1 to i, appending each number with a space before every one after the first — the Right Half Pyramid's shape, filled with counting numbers instead of stars.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printIncreasingNumberTriangle(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 result[i - 1] = row.toString();
11 }
12 return result;
13 }
14}Build with Range + JoinOptimal
Row i is just the numbers 1 through i, joined by spaces — build that range directly and join it, no manual index-and-space bookkeeping. C has no range/join built-in, so it keeps the explicit loop.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printIncreasingNumberTriangle(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 result[i - 1] = java.util.stream.IntStream.rangeClosed(1, i)
6 .mapToObj(String::valueOf)
7 .collect(java.util.stream.Collectors.joining(" "));
8 }
9 return result;
10 }
11}