Python 2221.py
class Solution:
def triangularSum(self, nums: List[int]) -> int:
# no smart stuff, just brute force
while len(nums) > 1:
for i in range(len(nums) - 1):
nums[i] += nums[i + 1]
nums.pop()
return nums[0] % 10
Difficulty
and has an acceptance rate of about 82% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Combinatorics
- Math
- Number Theory
- Simulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the “triangular sum” of an integer array by repeatedly collapsing the array until a single value remains. Each collapse replaces every adjacent pair with their sum, discarding the last element after each pass. When only one element is left, the result is reduced modulo 10 and returned. The algorithm works entirely in-place, reusing the original list to avoid extra allocations.
Core Logic
Repeated Collapse Loop
while len(nums) > 1:
...
The outer while loop drives the process. It continues as long as the list contains more than one element, guaranteeing that the collapse steps are applied until a solitary value is produced.
Pairwise Summation
for i in range(len(nums) - 1):
nums[i] += nums[i + 1]
Inside the loop, a forward for iteration visits every index except the final one. At each position i, the element at i is incremented by the value of its right neighbor i + 1. This in-place addition builds the next-level row of the triangular transformation without allocating a temporary container.
Truncating the List
nums.pop()
After all pairwise additions are performed, the last element of the list-now redundant because it has already contributed to the preceding sum-is removed with pop(). This operation shortens the list by one, preparing it for the next iteration of the outer loop.
Final Modulo Reduction
return nums[0] % 10
When the loop terminates, the list holds a single integer at index 0. The method returns this value reduced modulo 10, delivering the required single-digit triangular sum.
Edge-Case Handling
The algorithm naturally accommodates a list that initially contains exactly one element. In that scenario, the while condition fails immediately, and the method returns the sole element modulo 10 without entering the collapse logic. This behavior ensures correct output for the minimal non-empty input.
When the input list contains large integers, the code postpones any modulo operation until the very end. By accumulating full integer sums throughout the collapse, it preserves the exact arithmetic needed for the final digit, handling any magnitude of intermediate values that Python’s arbitrary-precision integers can represent.
Performance Optimizations
The implementation achieves efficiency through several deliberate choices:
-
In-Place Updates - By updating
nums[i]directly, the algorithm avoids creating auxiliary arrays for each level of the triangle. This reduces memory pressure and eliminates the overhead of copying data. -
Single Pop per Iteration - Removing the trailing element with
pop()is an O(1) operation in Python lists. Performing exactly one pop after each full pass keeps the list size tightly coupled to the number of remaining rows, ensuring that subsequent iterations work on a progressively smaller dataset. -
Deferred Modulo - Computing the modulo only after the final value is obtained prevents repeated division operations during the inner summation steps. This saves computational cycles, especially when the list is large and many additions are performed.
-
Minimal Loop Overhead - The inner
forloop iterates over a range derived from the current length of the list, guaranteeing that each element is visited exactly once per collapse. No extra index calculations or condition checks are introduced beyond the essential iteration.
Collectively, these choices allow the method to process the triangular sum with a modest memory footprint and a low constant factor in its runtime, making it well-suited for inputs of moderate size while preserving correctness for all valid integer lists.
ELI5 - Simplified Explanation
Imagine a line of numbered blocks sitting on a table. This code wants to make a new line of blocks based on the ones already there. To do this, the code looks at two blocks sitting right next to each other and adds their numbers together to make a new block for a shorter line. It keeps doing this, making the line smaller and smaller, until only one single block is left at the very end. Once that final block is the only one remaining, the process stops. Every time the numbers are added together, the code also makes sure to keep only the last digit of the result so the numbers stay nice and small.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | C# | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 119: Pascal's Triangle II
- problem 2243: Calculate Digit Sum of a String
- problem 2293: Min Max Game
Solved On The Same Day
- problem 1641: Count Sorted Vowel Strings
- problem 1829: Maximum XOR for Each Query
- problem 1833: Maximum Ice Cream Bars
- problem 1910: Remove All Occurrences of a Substring
- problem 2079: Watering Plants
- problem 2120: Execution of All Suffix Instructions Staying in a Grid
- problem 2161: Partition Array According to Given Pivot
- problem 2545: Sort the Students by Their Kth Score
- problem 2640: Find the Score of All Prefixes of an Array
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality