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
Find Triangular Sum of an Array INPUT nums = [1, 2, 3, 4, 5] 1 2 3 4 5 i=0 i=1 i=2 i=3 i=4 Triangular Reduction: 1 2 3 4 5 3 5 7 9 8 2 6 0 8 8 ALGORITHM STEPS 1 Check Length If n == 1, return nums[0] 2 Iterate In-Place For i from 0 to n-2 3 Compute Sum nums[i] = (nums[i]+nums[i+1])%10 4 Reduce Size Decrease n by 1, repeat Formula: newNums[i] = (nums[i] + nums[i+1]) % 10 Iterations: 5 --> 4 --> 3 --> 2 --> 1 Time: O(n^2) | Space: O(1) FINAL RESULT Triangular Sum: 8 OK After 4 iterations, array reduces to [8] [1,2,3,4,5] --> [3,5,7,9] [3,5,7,9] --> [8,2,6] [8,2,6] --> [0,8] [0,8] --> [8] Key Insight: In-place simulation modifies the array directly without extra space. Each pass computes pairwise sums modulo 10, reducing array length by 1. The process creates a triangular pattern, eventually leaving only one element - the triangular sum. This is similar to Pascal's Triangle with modular arithmetic. TutorialsPoint - Find Triangular Sum of an Array | In-Place Simulation Approach
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