Easy 2 solved 40.0% acceptance

Number Triangle

Build a triangle of increasing numbers.

What you'll learn

  • Build rows of growing length
  • Keep a counter across rows
  • Return a 2D list

Problem

Build a number triangle: row i (counting from 1) lists the numbers 1, 2, …, i.

Implement number_triangle(rows).

Input

rows: The number of rows.

Output

Return the triangle as a list of rows.

Constraints

0 ≤ rows ≤ 30

Examples

Example 1
Input:
rows = 3

Expected output:
expected = [
    [1],
    [1, 2],
    [1, 2, 3]
]
Input:
long long rows = 3;

Expected output:
std::vector<std::vector<long long>> expected = {
    {1},
    {1, 2},
    {1, 2, 3}
};
Input:
long rows = 3;

Expected output:
long[][] expected = new long[][] {
    new long[] {1},
    new long[] {1, 2},
    new long[] {1, 2, 3}
};

Explanation

Rows are [1], [1, 2] and [1, 2, 3].

Example 2
Input:
rows = 0

Expected output:
expected = []
Input:
long long rows = 0;

Expected output:
std::vector<std::vector<long long>> expected = {};
Input:
long rows = 0;

Expected output:
long[][] expected = new long[][] {};

Explanation

No rows were requested, so the triangle is empty.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Row i should contain the numbers from 1 up to i in order.

Hint 2

Grow each row by one element as you move downward.

Hint 3

When there are no rows, the result should simply be empty.

Expected complexity

O(rows^2) time, O(rows^2) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

Spoiler alert: 2 full solutions below Try solving it yourself first. You can still peek at other developers' code and AI reviews. Sign in and solve the challenge to join the discussion.