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. Building one row is trivial. What trips candidates is the direction and the boundary. The first row is the WIDEST, so you are counting down, not up. The narrowest row is one asterisk, not zero. Reach for the default forward range and you either return the triangle upside down or emit an empty row where the single asterisk belongs.


Break down the requirements

Step 1: Iterate widths high to low

Walk the widths from n down to 1, both ends included. Each value is exactly the asterisk count for that row, so there is no n - i arithmetic to get backwards.

Step 2: Turn each width into a row

A width becomes the string of that many asterisks directly. "*" * width 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 and 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