Problem 2221

Abstract / Summary

Given an array, compute the sum of all numbers in its triangular form row by row.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
8 lines | 282 bytes | submitted December 22, 2023 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 82% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Combinatorics
  • Math
  • Number Theory
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 for loop 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.81 | σ = 1.44

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
29 links | 16 authors | 9 languages

Videos

9 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

10 solutions   December 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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