#59Easy#25 in JPMorgan Chase's list· asked at 1 company
Average of All Elements in an Array
Problem
Given an integer array arr of size n, return the average (arithmetic mean) of its elements. Return the result as a floating-point number rounded to two decimal places, or as an integer floor if the problem demands integer output. Handle the empty array by returning 0.
Input / Output
- Input: integer array
arr. - Output: the mean.
Examples
| arr | Output |
|---|---|
[1, 2, 3, 4, 5] | 3.0 |
[10, 20] | 15.0 |
[7] | 7.0 |
[-3, 3] | 0.0 |
[] | 0 |
Constraints
0 <= n <= 10^6-10^9 <= arr[i] <= 10^9
Approach
Sum all elements and divide by n. The interesting parts are the edge cases the interviewer is really asking about:
- Overflow. With
n = 10^6and values up to10^9, the sum reaches10^15, which overflows a 32-bit integer. Use 64-bit (long) or accumulate in floating point. - Integer vs. floating division. In C, C++ and Java,
sum / nwith both operands integers truncates. Cast one operand todoublefirst. - Empty input. Division by zero — return 0 or raise, but decide explicitly.
- Streaming / running average. If values arrive one at a time, keep
countandmeanand update withmean += (x - mean) / count— this avoids storing the sum and is numerically stabler for very long streams (Welford's method). - Sliding-window average (average of the last
kelements) is the natural follow-up and uses a circular buffer plus a running sum.
Complexity
- Time: O(n)
- Space: O(1)
Reference solution (Python)
def average(arr):
if not arr:
return 0
return round(sum(arr) / len(arr), 2)
def running_mean(stream):
mean, count = 0.0, 0
for x in stream:
count += 1
mean += (x - mean) / count
return mean
Test cases
| Input | Expected |
|---|---|
[1,2,3,4,5] | 3.0 |
[10,20] | 15.0 |
[] | 0 |
running_mean([2,4,6]) | 4.0 |