โ† Morgan Stanley questions
CodingReported in a candidate post, Apr 2025

Find the number closest to the average of an array

Filed under Morgan Stanley

Free read 2 of 3

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.

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

  1. 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.

Solution

O(n) time, O(1) space

Python
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.