Back to questions
You are given an integer array , where each element in it is a single digit (0-9).
The triangular sum of is the value of the only element present in nums after the following process terminates:
Return the triangular sum of nums.
Input: nums =
Iteration #1: Form = [(1 + 3) % 10, (3 + 5) % 10, (5 + 7) % 10] = [4, 8, 2].
Iteration #2: Form = [(4 + 8) % 10, (8 + 2) % 10] = [2, 0].
Iteration #3: Form = [(2 + 0) % 10] = [2].
The triangular sum of is 2.
Input: nums =
Iteration #1: Form = [(9 + 7) % 10, (7 + 5) % 10, (5 + 3) % 10] = [6, 2, 8].
Iteration #2: Form = [(6 + 2) % 10, (2 + 8) % 10] = [8, 0].
Iteration #3: Form = [(8 + 0) % 10] = [8].
The triangular sum of is 8.
This is the type of question where you will just do what the problem statement says. We will just follow the rules until we are left with an array with only one number.
Here is the code:
Since there isn't much optimization to do, the interviewer might ask you to solve the problem using multiple approaches during an interview. One other way of solving this problem is through recursion.
In recursion, the base case is the simplest version of the problem where the recursion stops. For this problem, the base case occurs when we are left with just one number in the list. This is the final triangular sum, so we simply return it.
The recursive case is where the problem is broken down into smaller subproblems. Here’s what we do in each recursive step:
Here is the full recursive solution: