Average of a List of Integers, Returning 0 for an Empty List
Company: Waymo
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Write a function that returns the arithmetic mean of a list of integers and returns 0 for an empty list. A warm-up from a timed data science assessment that tests careful handling of the empty case and floating-point division.
Constraints
- 0 <= len(table) <= 10^5
- -10^6 <= table[i] <= 10^6
- |sum(table)| <= 10^11, so the sum is exact in a 64-bit integer and in a double
- The sum can exceed 2^31 - 1: accumulate it in a 64-bit integer (long in Java, long long in C++)
- Return 0.0 for an empty list; otherwise return sum / len as an unrounded IEEE 754 double
Examples
Input: ([3, 4, 8],)
Expected Output: 5.0
Explanation: Source example 1: (3 + 4 + 8) / 3 = 5.0.
Input: ([],)
Expected Output: 0.0
Explanation: Source example 2 / empty input: an empty list returns 0.0 instead of raising.
Hints
- Handle the empty list before dividing, since dividing by a length of zero is undefined.
- Think about how large the running total can get relative to the range of a 32-bit integer.
- Make sure the final division is floating-point division, not integer division: [1, 2] should give 1.5.