We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Triangular Sum of an Array

Number: 2324

Difficulty: Medium

Paid? No

Companies: Amazon, Zoho


Problem Description

Given an array of digits (0-indexed) where each element is between 0 and 9, repeatedly form a new array by adding each pair of adjacent elements and taking the sum modulo 10. This process continues until only one element remains. The final single element is the triangular sum of the array.


Key Insights

  • The operation involves pairwise addition of adjacent elements modulo 10.
  • The process simulates reduction of the array until only one value remains.
  • Each reduction step decreases the array size by one, leading to a quadratic time behavior in the worst case.
  • Although there is a combinatorial formula involving binomial coefficients, simulation is straightforward given the constraint sizes.

Space and Time Complexity

Time Complexity: O(n^2) in the worst-case scenario due to iterative pairwise reductions. Space Complexity: O(n) extra space to store the new array at each iteration.


Solution

We simulate the process of forming new arrays until only one element remains. At each step, we iterate through the current array and form a new array where each element is the sum of two adjacent elements modulo 10. The key data structure is the array itself, and the primary algorithmic approach is iterative simulation. This approach is efficient enough given the constraints, and it directly mirrors the problem description.


Code Solutions

# Function to compute the triangular sum of an array
def triangularSum(nums):
    # Loop until only one element remains
    while len(nums) > 1:
        new_nums = []  # Create a new list for the reduced array
        # Compute the sum modulo 10 for each adjacent pair
        for i in range(len(nums) - 1):
            new_nums.append((nums[i] + nums[i+1]) % 10)
        # Update the array with the new computed values
        nums = new_nums
    # The remaining element is the triangular sum
    return nums[0]

# Example usage:
example_nums = [1, 2, 3, 4, 5]
print(triangularSum(example_nums))  # Expected output: 8
← Back to All Questions