Minimum Average of Smallest and Largest Elements - Problem

You have an array of floating point numbers averages which is initially empty. You are given an array nums of n integers where n is even.

You repeat the following procedure n / 2 times:

  • Remove the smallest element, minElement, and the largest element maxElement, from nums.
  • Add (minElement + maxElement) / 2 to averages.

Return the minimum element in averages.

Input & Output

Example 1 — Basic Case
$ Input: nums = [7,8,3,4,15,13,4,1]
Output: 5.5
💡 Note: After sorting: [1,3,4,4,7,8,13,15]. Pairs: (1,15)→8.0, (3,13)→8.0, (4,8)→6.0, (4,7)→5.5. Minimum average is 5.5.
Example 2 — Even Distribution
$ Input: nums = [1,9,8,2,3,7]
Output: 5.0
💡 Note: After sorting: [1,2,3,7,8,9]. Pairs: (1,9)→5.0, (2,8)→5.0, (3,7)→5.0. All averages are 5.0, so minimum is 5.0.
Example 3 — Minimum Size
$ Input: nums = [1,2]
Output: 1.5
💡 Note: Only one pair possible: (1,2) with average (1+2)/2 = 1.5.

Constraints

  • 2 ≤ nums.length ≤ 105
  • nums.length is even
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Minimum Average of Smallest and Largest Elements INPUT nums = [7,8,3,4,15,13,4,1] 7 8 3 4 15 13 4 1 Sorted Array: 1 3 4 4 7 8 13 15 MIN MAX n = 8 (even) Iterations: n/2 = 4 Use two pointers approach ALGORITHM STEPS 1 Sort Array O(n log n) sorting 2 Initialize minAvg Track minimum average 3 Two Pointers Left (min) + Right (max) 4 Track Min Average Update if smaller found Iterations: i=1: (1+15)/2 = 8.0 i=2: (3+13)/2 = 8.0 i=3: (4+8)/2 = 6.0 i=4: (4+7)/2 = 5.5 [MIN] minAvg updated: 5.5 FINAL RESULT averages array built: 8.0 8.0 6.0 5.5 MIN Output: 5.5 OK - Minimum found! Complexity: Time: O(n log n) Space: O(1) optimized Key Insight: After sorting, pair smallest (left) with largest (right) elements using two pointers. Track minimum average directly instead of storing all averages --> O(1) space. The minimum average always comes from pairing elements closest to the middle of sorted array. TutorialsPoint - Minimum Average of Smallest and Largest Elements | Optimized - Direct Minimum Tracking
Asked in
Amazon 15 Google 12 Microsoft 8
8.5K Views
Medium Frequency
~15 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen