Array Sum and Average - Problem

Given an array of numbers, calculate and return an array containing the sum, average, minimum, and maximum values from the input array.

The output array should contain exactly 4 elements in this order:

  • [0]: Sum of all elements
  • [1]: Average of all elements (as a decimal)
  • [2]: Minimum element
  • [3]: Maximum element

Note: The average should be calculated as a floating-point number, not rounded to an integer.

Input & Output

Example 1 — Basic Array
$ Input: nums = [1,5,3,9,2]
Output: [20,4.0,1,9]
💡 Note: Sum: 1+5+3+9+2 = 20, Average: 20/5 = 4.0, Min: 1, Max: 9
Example 2 — Negative Numbers
$ Input: nums = [-2,4,-1,7]
Output: [8,2.0,-2,7]
💡 Note: Sum: -2+4+(-1)+7 = 8, Average: 8/4 = 2.0, Min: -2, Max: 7
Example 3 — Single Element
$ Input: nums = [42]
Output: [42,42.0,42,42]
💡 Note: With one element, sum, average, min, and max are all the same value: 42

Constraints

  • 1 ≤ nums.length ≤ 104
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
INPUTALGORITHMRESULT15392Array: [1,5,3,9,2]Need to calculate:• Sum of elements• Average value• Minimum value• Maximum value1Initialize: sum=1, min=1, max=12Loop through remaining elements3Update sum, min, max each step4Calculate average = sum / lengthFinal: sum=20, min=1, max=9Average = 20/5 = 4.0Statistics Array[20, 4.0, 1, 9]Sum: 20Average: 4.0Min: 1, Max: 9Key Insight:Single pass through the array can collect all statistics simultaneously, avoiding multiple loopsTutorialsPoint - Array Sum and Average | Single Pass Approach
Asked in
Google 15 Amazon 12 Microsoft 8
12.0K Views
Medium Frequency
~8 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen