Skip to the content

Yang Hui's triangle

Problem

The master of the imperial school in Hangzhou asks a student for a single row of the triangle Yang Hui published in 1261. The book is not lent out, so the student rebuilds it from the top, row by row, each one from the row just written.

Write a function that takes n, a whole number from 0 up, and returns row n of the triangle as a list of whole numbers; row n has n + 1 numbers. Row 0 is [1] and row 1 is [1, 1]. Every row after that starts and ends with 1, and each position i in the middle holds the sum of positions i - 1 and i of the row above.

With n equal to 4: [1], [1, 1], [1, 2, 1] (1 + 1), [1, 3, 3, 1] (1 + 2 and 2 + 1) and, from row 3, row 4: 1 + 3, 3 + 3 and 3 + 1 give [1, 4, 6, 4, 1]. That is what you return.

Examples

  • The example

    4 → [1, 4, 6, 4, 1]

  • Row 0

    0 → [1]

  • Row 1

    1 → [1, 1]

  • The first one with a middle number

    2 → [1, 2, 1]

  • Row 3

    3 → [1, 3, 3, 1]

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def triangle_row(n):
    pass

JavaScript

function triangleRow(n) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →