Pascal triangle digit encryption
I was asked this
No reports yet. Sign in to say where you were asked it.
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 to10^5) - every element is between
0and9
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 - 2rounds,O(n^2)time andO(1)extra space, fine forn <= 1000. - Formats the result as a two-character string so
07keeps its zero. - For
n = 10^5: each final digit is a weighted sum of the inputs with binomial weightsC(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
nto10^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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
