Top-Heavy

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L3
Asked in
Kinesso

Problem

A console report renders a quick text gauge from a single count: given a positive integer n, return n lines of asterisks where the first line is the widest with n of them and every line below loses one, ending at a single asterisk.

The widest row leads, and everything below it narrows.

Example

Input:

n = 4

Output:

["****","***","**","*"]

Worked solution and explanation

What this is really testing

Strip the costume and this is a row of widths counting down: n, n-1, ..., 1, each rendered as that many asterisks. Everyone gets the rows right; the only place candidates trip is the direction. The first row is the WIDEST, so you are counting DOWN, not up, and the off-by-one (starting at n, stopping at 1) is where a rushed answer produces n+1 rows or an empty last row.


Break down the requirements

Step 1: Iterate widths high to low

Walk the widths from n down to 1. Each value is exactly the asterisk count for that row, so you never compute n minus anything.

Step 2: Turn each width into a row

A width w becomes the string of w asterisks directly. String repetition does the work in one expression.

Step 3: Return the rows

Collect the rows in order into a list of strings. The first element is the widest, the last is a single asterisk.


The solution

Decreasing widths, one pass
def inverted_triangle(n: int) -> list[str]:
    return ["*" * width for width in range(n, 0, -1)]

Common follow-up questions