Problem Description
Given an even-length array, repeatedly remove the smallest and largest elements, compute their average, and return the number of distinct averages obtained from these operations.
Key Insights
- Sorting the array lets us easily pair the smallest and largest elements.
- The sorted order ensures that the smallest and largest elements are always at the opposite ends.
- Using a set to store averages automatically handles distinct values.
- The process continues until no elements remain in the array.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting, where n is the number of elements in the array. Space Complexity: O(n) for the sorted array copy and storage of distinct averages.
Solution
The approach involves first sorting the input array so that the smallest and largest elements are located at the beginning and end respectively. Then, use two pointers: one starting at the beginning (left pointer) and the other at the end (right pointer). In each iteration, compute the average of the numbers at the left and right pointers, store it in a set to maintain distinct averages, and move the pointers towards the center. This continues until the pointers cross. Finally, return the size of the set containing distinct averages.