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?- A. [1, 5, 10, 10, 5, 1] 64
- B. [1, 5, 10, 5, 1] 128
- C. [1, 5, 10, 10, 5, 1] 128
- 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
- Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1. python def no11(n)…
- Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three…
- Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed…
- Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain…
- Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total…
- Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts. python def intbreak(n): dp = [0, 1]…