Print a Continuously Increasing Number Triangle
Solve this ProblemEasy10–15 min
Topics
BasicsPatternsLoopsMath
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of Floyd's Triangle — a continuously counting-up sequence where row i holds the next i numbers, and the count never resets between rows.
This is easy to confuse with the Increasing Number Triangle, which restarts at 1 every row — here, row 2 picks up exactly where row 1 left off. The shared counterShared CounterA counter variable declared OUTSIDE the row loop, so it keeps climbing across every row instead of resetting. version makes that explicit by carrying one counter variable through the whole computation. The running range sliceRunning Range SliceComputing each row's starting number directly from the triangular-number formula i(i-1)/2 + 1, so any single row can be produced without having computed the rows before it. version instead computes, for any row, exactly where in the overall count it should start — no running state required at all.
Test Case 1:
Input:n = 3
Output:["1", "2 3", "4 5 6"]
Explanation:The count never resets between rows — row 2 continues right where row 1 left off.
Test Case 2:
Input:n = 1
Output:["1"]
Explanation:Just the first number.
Constraints
- ◆
1 ≤ n ≤ 9
Try the Dry Run
Approach & Solutions
Nested Loops — Shared CounterGood
Unlike the Increasing Number Triangle (where every row restarts at 1), this one keeps a single counter that lives OUTSIDE the row loop and keeps climbing across every row — row i gets the next i numbers in the overall count, wherever it left off. This classic sequence is known as Floyd's Triangle.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printFloydsTriangle(int n) {
3 String[] result = new String[n];
4 int counter = 1;
5 for (int i = 1; i <= n; i++) {
6 StringBuilder row = new StringBuilder();
7 for (int j = 1; j <= i; j++) {
8 if (j > 1) row.append(' ');
9 row.append(counter);
10 counter++;
11 }
12 result[i - 1] = row.toString();
13 }
14 return result;
15 }
16}Build with a Running Range SliceOptimal
Row i's numbers are a slice of the overall count: they start right after the (i − 1)(i − 2)/2 + ... numbers used by every earlier row — specifically at i(i − 1)/2 + 1 — and run for i numbers. Compute that start directly with the triangular-number formula instead of carrying a counter across iterations.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printFloydsTriangle(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 int start = i * (i - 1) / 2 + 1;
6 result[i - 1] = java.util.stream.IntStream.range(start, start + i)
7 .mapToObj(String::valueOf)
8 .collect(java.util.stream.Collectors.joining(" "));
9 }
10 return result;
11 }
12}