Find Triangular Sum of an Array - Problem

You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).

The triangular sum of nums is the value of the only element present in nums after the following process terminates:

  1. Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.
  2. For each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.
  3. Replace the array nums with newNums.
  4. Repeat the entire process starting from step 1.

Return the triangular sum of nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4,5]
Output: 8
💡 Note: Layer by layer: [1,2,3,4,5] → [3,5,7,9] → [8,2,6] → [0,8] → [8]. The triangular sum is 8.
Example 2 — Small Array
$ Input: nums = [5]
Output: 5
💡 Note: Single element array: the triangular sum is the element itself, which is 5.
Example 3 — Two Elements
$ Input: nums = [7,9]
Output: 6
💡 Note: Two elements: (7 + 9) % 10 = 16 % 10 = 6. The triangular sum is 6.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 9

Visualization

Tap to expand
Triangular Sum Process2749Original Array913Layer 1: [9,1,3]04Layer 2: [0,4]4Triangular Sum = 4
Understanding the Visualization
1
Input Array
Start with array [2,7,4,9] of digits 0-9
2
Triangular Reduction
Layer by layer: sum adjacent pairs modulo 10 until one element remains
3
Final Result
The triangular sum is the last remaining element: 4
Key Takeaway
🎯 Key Insight: The triangular sum creates a Pascal's triangle pattern where each element's final contribution follows binomial coefficients
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen