Problem Statement in English
You’re 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 single digit value obtained by performing the following operation until there is only one element left in nums:
- Create a new array
new_numsof the same length asnums. - For each index
iinnums, setnew_nums[i]to the sum ofnums[i]andnums[i + 1](modulo 10). - Replace
numswithnew_nums. - Repeat until
numshas only one element.
Return the triangular sum of nums.
Approach
The problem is straightforward. We need to keep reducing the array until we have a single element left.
Solution in Python
class Solution:
def triangularSum(self, nums: List[int]) -> int:
buffer = []
while len(nums) > 1:
buffer = []
for i in range(len(nums) - 1):
buffer.append((nums[i] + nums[i + 1]) % 10)
nums = buffer
return nums[0]
Complexity
Time: $O(n^2)$, where $n$ is the length of the input array
nums. In the worst case, we may need to perform the reduction operation $n$ times, and each operation takes $O(n)$ time.Space: $O(n)$, for the temporary buffer used to store the intermediate results during the reduction process.
And we are done.