Find the number closest to the average of an array
Filed under Morgan Stanley
Free read 2 of 3Ask whether values can be negative or zero, how to break ties (the candidate here wanted to confirm this before coding), whether the array can be empty and whether the average is real-valued.
The question
Given an array of positive integers, find the element that is closest to the average of all the numbers.
Constraints
- Array of positive integers, length >= 1
- On a tie return the smaller value (assumed)
- O(n) time
Examples
- Input
- [1, 2, 3, 10]
- Output
- 3
- Why
- Average is 4; 3 is distance 1 away
- Input
- [1, 2]
- Output
- 1
- Why
- Average 1.5 is a tie, return the smaller value
Approach
Ask whether values can be negative or zero, how to break ties (the candidate here wanted to confirm this before coding), whether the array can be empty and whether the average is real-valued.
Compute the average in one pass, then scan again for the element with the smallest absolute difference: O(n) time, O(1) space. This is already optimal.
Compare abs(x * n - sum) instead of abs(x - sum / n) so everything stays in integer arithmetic.
Single element, ties (for example [1, 2] with average 1.5; pick the smaller by convention), duplicates and very large sums that could overflow a 32-bit int.
Solution
O(n) time, O(1) space
def closest_to_average(nums):
n, total = len(nums), sum(nums)
# |x - total/n| is proportional to |x*n - total|; this avoids floating point
return min(nums, key=lambda x: (abs(x * n - total), x))
Tips
- What they are testing: Tests clean two-pass code, correct loop bounds and the habit of clarifying inputs before coding.
- Common mistake: Off-by-one loop bounds, integer division when computing the average, and overflowing the sum in fixed-width languages.
Related Morgan Stanley questions
Collected from public candidate posts and coding forums. Updated Nov 2026.