Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Repeated adjacent addition makes each original position contribute according to Pascal's triangle. After n - 1 reductions, the coefficient of nums[i] is C(n - 1, i). Reducing modulo ten at every step or only after the final weighted sum gives the same remainder.
Approach
For each original element, compute its binomial coefficient, multiply it by the element, and add the product to an exact-integer accumulator. Return the final sum modulo ten. The reference solutions evaluate coefficients rather than explicitly building the shrinking intermediate rows. A one-element array uses coefficient C(0, 0) = 1 and is returned unchanged.
class Solution:
def triangularSum(self, nums: List[int]) -> int:
n = len(nums)
res = 0
for i, v in enumerate(nums):
res += v * comb(n - 1, i)
return res % 10Complexity analysis
Let n = nums.length. JavaScript performs O(n^2) exact-integer multiplication/division iterations when independently computing all coefficients. This is an arithmetic-operation count, not a bit-time bound: coefficients and the accumulator have O(n) bits. Elementary arithmetic gives a conservative O(n^3 log(n + 1)) bit-time bound for that helper. Python makes n calls to math.comb; its actual coefficient-computation cost depends on the runtime implementation. Writing C(n) for the maximum bit cost of one such call, Python takes O(n*C(n) + n^2) bit time. Live coefficients and the accumulator occupy O(n) bits, in addition to any internal math.comb workspace; JavaScript's explicit helper needs O(n) auxiliary bits.
