#30958Medium

Pascal's triangle

Given a number N, construct the Pascal's triangle with N rows. Learn array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll construct Pascal's triangle at the type level, producing a tuple of tuples representing N rows of the triangle using recursive type arithmetic.

Challenge Instructions: Pascal's triangle

Medium

Given a number N, construct the Pascal's triangle with N rows. Wikipedia

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<Pascal<1>, [[1]]>>,
  Expect<Equal<Pascal<3>, [[1], [1, 1], [1, 2, 1]]>>,
  Expect<
    Equal<Pascal<5>, [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]>
  >,
  Expect<
    Equal<
      Pascal<7>,
      [
        [1],
        [1, 1],
        [1, 2, 1],
        [1, 3, 3, 1],
        [1, 4, 6, 4, 1],
        [1, 5, 10, 10, 5, 1],
        [1, 6, 15, 20, 15, 6, 1],
      ]
    >
  >,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type Length<T extends unknown[]> = T['length']
 
type MakeArray<N extends number, T extends 1[] = []> =
  Length<T> extends N ? T : MakeArray<N, [...T, 1]>
 
type Add<A extends number, B extends number> =
  Length<[...MakeArray<A>, ...MakeArray<B>]>
 
type NextRow<T extends number[], Result extends number[] = [1]> =
  T extends [infer A extends number, infer B extends number, ...infer Rest extends number[]]
    ? NextRow<[B, ...Rest], [...Result, Add<A, B>]>
    : [...Result, 1]
 
type Pascal<
  N extends number,
  Prev extends number[] = [1],
  Result extends number[][] = [[1]],
> = Length<Result> extends N
  ? Result
  : Pascal<N, NextRow<Prev>, [...Result, NextRow<Prev>]>

How it works:

This challenge helps you understand recursive type-level arithmetic and tuple construction, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge