Return Elements Greater Than the Overall Average
SquarepointSoftware Engineer · HR ScreenLast updated
This problem tests your ability to perform a two-pass linear scan on an array to compute an aggregate statistic and filter elements, emphasizing space complexity and data integrity.
Problem Statement
Given an array of integers, return a new list containing only the elements that are strictly greater than the arithmetic mean of all elements in the input list.
Your implementation should:
- Maintain the relative order of the original elements.
- Include duplicates if they satisfy the condition.
- Not modify the input array.
- Handle negative numbers correctly.
Function Signature
def get_elements_above_average(nums: List[int]) -> List[int]:
Constraints
n(length ofnums) is in the range[0, 10^6].- Each element
nums[i]is between-10^9and10^9. - You should aim for
O(n)time complexity and avoid unnecessary memory overhead.
Examples
Example 1:
Input: nums = [1, 2, 3, 4, 5]
Average: 3.0
Output: [4, 5]
Explanation: Only 4 and 5 are strictly greater than 3.
Example 2:
Input: nums = [10, -10, 5, 5]
Average: 2.5
Output: [10, 5, 5]
Explanation: 10, 5, and 5 are greater than 2.5.
Edge Cases
- What should the function return if the list is empty? (Return an empty list)
- What happens if all elements are equal? (The average equals the elements, so return an empty list)
- Ensure you handle potential integer overflow during the summation process if using lower-level languages.
Hints
Hint 1
The arithmetic mean is calculated as the sum of all elements divided by the count of elements.
Hint 2
Perform one pass to calculate the total sum and a second pass to filter the elements based on the calculated mean.
Hint 3
Use floating-point division when comparing the mean, or multiply both sides of the inequality by the list length to work entirely with integers to avoid precision issues.
Follow-up questions
- How would you modify your solution if the input list was a stream of numbers too large to fit in memory?
- If the input array were sorted, could you optimize the finding of elements greater than the average?
- How would you handle the case where the calculation of the mean results in a precision error using standard floating-point types?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.