Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row.

Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row.
def pascal_row(k):
    row = [1]
    for _ in range(k):
        row = [1] + [row[i] + row[i + 1] for i in range(len(row) - 1)] + [1]
    return row
print(pascal_row(5), sum(pascal_row(7)))
What is printed?
  1. A. [1, 5, 10, 10, 5, 1] 64
  2. B. [1, 5, 10, 5, 1] 128
  3. C. [1, 5, 10, 10, 5, 1] 128
  4. D. [1, 4, 6, 4, 1] 128

Correct answer: C. [1, 5, 10, 10, 5, 1] 128

Each inner entry is the sum of the two above it, so row k holds C(k, 0..k): row 5 = 1, 5, 10, 10, 5, 1 (6 entries – row 4 has 5). The entries of row k sum to 2ᵏ, so row 7 sums to 128. O(k²).

More Coding Interview Problems questions

Exams that ask this topic