Find Triangular Sum of an Array (LeetCode 2221): Solution and Explanation

Medium
Array
Math
Simulation
Combinatorics

Collapse an array of digits row by row, replacing each adjacent pair with its sum mod 10, until one digit is left. Return that digit.

Intuition

The statement already describes an algorithm, and the limits allow it. With n up to 1000 the rows add up to about 500,000 additions, which is quick in every language.

The useful observation is about memory. Row k+1 only needs neighbouring cells of row k. If you overwrite nums[i] from left to right, nums[i + 1] still holds the old value when you read it, so a single array is enough.

Drawing the rows as a triangle shows why the name fits, and also why the answer is a weighted sum. Each top digit flows down to the bottom along every path through the triangle, and the number of such paths from position i is the binomial coefficient C(n - 1, i).

So the answer equals the sum of C(n - 1, i) times nums[i], mod 10. That gives an O(n) method if you can compute binomials mod 10, but it needs care because 10 is not prime.

Approach: In-place simulation

  1. Let n = len(nums).
  2. For size from n - 1 down to 1, loop i from 0 to size - 1.
  3. Set nums[i] = (nums[i] + nums[i + 1]) % 10. Going left to right means nums[i + 1] is still from the previous row.
  4. After the last pass only nums[0] matters. Return it.

Step-by-step example

nums = [1,2,3,4,5]
  1. size = 4: the first row becomes [3,5,7,9] (1+2, 2+3, 3+4, 4+5).
  2. size = 3: [3+5, 5+7, 7+9] mod 10 = [8,2,6].
  3. size = 2: [8+2, 2+6] mod 10 = [0,8].
  4. size = 1: (0+8) mod 10 = 8, so the triangular sum is 8.

Code: Python, Java, C++

1class Solution:
2    def triangularSum(self, nums: List[int]) -> int:
3        n = len(nums)
4        for size in range(n - 1, 0, -1):
5            for i in range(size):
6                nums[i] = (nums[i] + nums[i + 1]) % 10
7        return nums[0]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Row sizes are n - 1, n - 2, ..., 1, which add up to n(n - 1) / 2 constant-time updates.

Space

O(1)

The rows are written over the input array, so no extra arrays are created.

Other approaches

New array per row (time O(n^2), space O(n))

Build newNums each round exactly as the statement says. It is the most literal version and is easy to check, at the price of allocating n - 1 arrays.

Binomial coefficients mod 10 (time O(n log n), space O(1))

Compute C(n - 1, i) mod 10 for every i and return the weighted sum mod 10. Since 10 = 2 x 5, compute the coefficients mod 2 and mod 5 with Lucas's theorem and combine them, or track the factors of 2 and 5 separately while updating C(n-1, i) incrementally.

Common mistakes

  • Updating right to left in place. That overwrites nums[i + 1] before nums[i] reads it, mixing two rows.
  • Forgetting the mod 10 at each step. The digits would grow like binomial coefficients and overflow 32-bit integers for large n.
  • Not handling n = 1. The loop must run zero times and the single digit is the answer.
  • Trying the binomial formula with modular inverses mod 10. Inverses do not exist for multiples of 2 and 5, so that shortcut silently gives wrong answers.

Frequently asked questions

Why is overwriting nums safe?

When computing nums[i] for the new row you read nums[i] and nums[i + 1]. Moving left to right, nums[i + 1] has not been updated yet in this pass, so both values still belong to the previous row.

How does this relate to Pascal's triangle?

Each cell is the sum of the two cells above it, just like Pascal's triangle turned upside down. Counting paths from top position i to the bottom gives C(n - 1, i), so the result is the binomial-weighted sum of the inputs mod 10.

Is O(n^2) fast enough?

Yes. For n = 1000 that is under 500,000 simple additions, which runs in a few milliseconds in compiled languages and well within limits in Python.