Frontend School

Sum of Deep Event Values

DSA
easy

Sum of Deep Event Values

Easy
Recursion
Arrays
Data Structures

Overview

Clevertap helps businesses understand user behavior by collecting and analyzing event data. For advanced analytics and reporting, event metrics are sometimes aggregated into hierarchical structures, representing different segments or user journeys. To get a complete picture, we often need to sum up these values across all levels of nesting.

What you need to do / Task

Your task is to implement a function sumDeepValues that takes a nested array. This array can contain either numbers or other nested arrays (which themselves can contain numbers or further nested arrays). The function should calculate and return the total sum of all numbers present at any level within this nested structure.

Input & output

  • Input:
    • nestedArray: An array ((number | number[])[]) where each element is either a number or another array. The nested arrays can contain further numbers or nested arrays.
  • Output:
    • A number representing the sum of all numbers found in the nestedArray at any level.

Clarifications

  • The input nestedArray will only contain numbers or arrays. You don't need to handle other data types like strings, booleans, or objects.
  • Numbers can be positive, negative, or zero.
  • An empty array should contribute 0 to the total sum.

Examples

1

Example 1

Input:

nestedArray = [1, 2, 3]

Output:

6

Note:

1 + 2 + 3 = 6

2

Example 2

Input:

nestedArray = [1, [2, 3], 4]

Output:

10

Note:

1 + (2 + 3) + 4 = 10

3

Example 3

Input:

nestedArray = [1, [2, [3, []], 4], 5, [-1]]

Output:

14

Note:

1 + (2 + (3 + 0) + 4) + 5 + (-1) = 1 + 9 + 5 - 1 = 14

Constraints

Constraints & assumptions

  • The maximum nesting depth of arrays will not exceed 10 levels.
  • The total number of numeric elements across all levels will not exceed 1000.
  • All numbers are integers within the standard safe integer range (Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER).
  • The input nestedArray itself can be empty.

What interviewers evaluate

  • Correctness of Recursive Logic: Does the solution correctly identify base cases and recursive steps for summing elements?
  • Clarity and Readability: Is the code clean, well-structured, and easy to understand?
  • Efficiency: Does the solution traverse the structure without unnecessary computations?
  • Edge Case Handling: Does the solution correctly handle empty arrays or arrays with only numbers/only nested arrays?

Loading editor...