Find Triangular Sum of an Array — LeetCode 2221 Python Solution

MediumArrayMathCombinatoricsSimulation
Problem
#2221
Reading time
2 min

The 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: Let nums comprise of n elements.

Example

Input
nums = [1,2,3,4,5]
Output
8
Explanation
The above diagram depicts the process from which we obtain the triangular sum of the array.

Python solution

Python
class Solution:
    def triangularSum(self, nums: List[int]) -> int:
        for k in range(len(nums) - 1, 0, -1):
            for i in range(k):
                nums[i] = (nums[i] + nums[i + 1]) % 10
        return nums[0]

Complexity

MeasureComplexity
TimeO(n^2), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2221. Find Triangular Sum of an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math and Combinatorics.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2221. Find Triangular Sum of an Array?
LeetCode 2221. Find Triangular Sum of an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2221. Find Triangular Sum of an Array?
The Python solution on this page runs in O(n^2), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 2221. Find Triangular Sum of an Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2221. Find Triangular Sum of an Array cover?
LeetCode 2221. Find Triangular Sum of an Array is tagged Array, Math, Combinatorics and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview