← Questions

Pascal triangle digit encryption

0
AmazonCoding

A coding interview question asked at Amazon. It tests simulation, math and combinatorics.

Digits are encrypted by folding them down an upside-down Pascal's triangle.

You get a list of n digits (each 0-9). In one round, replace the list with the sums of each pair of neighbours, keeping only the last digit of each sum ((a + b) % 10). The list gets one shorter each round. Stop when exactly two digits remain.

Implement:

def encrypt(digits: list[int]) -> str

Return the final two digits as a two-character string. Keep a leading zero ("07", not "7").

Constraints

  • 2 <= n <= 1000 (a follow-up raises this to 10^5)
  • every element is between 0 and 9

Example 1

digits = [1, 2, 3, 4]
round 1: [3, 5, 7]
round 2: [8, 2]
output: "82"

Example 2

digits = [0, 7]
already two digits
output: "07"

Clarifying questions

  • If the input already has exactly two digits, is it returned as is (example 2)?
  • Is the output always exactly two characters, keeping a leading zero?
  • For the follow-up size, is O(n^2) still acceptable, or is a near-linear method needed?
  • Can the input list be modified in place?

What a strong answer covers

  • Simulates the rounds in place on one list: n - 2 rounds, O(n^2) time and O(1) extra space, fine for n <= 1000.
  • Formats the result as a two-character string so 07 keeps its zero.
  • For n = 10^5: each final digit is a weighted sum of the inputs with binomial weights C(n - 2, i), all mod 10.
  • Notes that division is not allowed mod 10, so the weights are computed mod 2 and mod 5 separately (Lucas's theorem) and combined with the Chinese remainder theorem, giving O(n log n) or better.
  • Compares the formula with the simulation on random inputs.

Follow-ups

  • Raise n to 10^5 (the binomial approach).
  • Stop at one digit instead of two.
  • Use a different modulus, such as a prime, where division is allowed.

Where it's asked

What it tests

simulation · math · combinatorics

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding