Number of Distinct Averages - Problem

You are given a 0-indexed integer array nums of even length.

As long as nums is not empty, you must repetitively:

  • Find the minimum number in nums and remove it.
  • Find the maximum number in nums and remove it.
  • Calculate the average of the two removed numbers.

The average of two numbers a and b is (a + b) / 2.

For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.

Return the number of distinct averages calculated using the above process.

Note that when there is a tie for a minimum or maximum number, any can be removed.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,1,4,0,3,5]
Output: 2
💡 Note: Removing pairs: (0,5)→avg=2.5, (1,4)→avg=2.5, (3,4)→avg=3.5. Distinct averages: {2.5, 3.5}, so return 2
Example 2 — All Same Average
$ Input: nums = [1,100]
Output: 1
💡 Note: Only one pair possible: (1,100)→avg=50.5. Only one distinct average, so return 1
Example 3 — Multiple Duplicates
$ Input: nums = [1,2,3,1,2,3]
Output: 1
💡 Note: After sorting [1,1,2,2,3,3]: pairs (1,3)→avg=2, (1,3)→avg=2, (2,2)→avg=2. All same average, return 1

Constraints

  • 2 ≤ nums.length ≤ 100
  • nums.length is even
  • 0 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Number of Distinct Averages INPUT nums array (even length) 4 1 4 0 3 5 0 1 2 3 4 5 Sorted: 0 1 3 4 4 5 min max nums = [4,1,4,0,3,5] Length: 6 (even) ALGORITHM STEPS 1 Sort Array Sort nums ascending 2 Two Pointers left=0, right=n-1 3 Calculate Averages (min + max) / 2 4 Use Set Store distinct averages Iterations: Round 1: (0+5)/2 = 2.5 Round 2: (1+4)/2 = 2.5 Round 3: (3+4)/2 = 3.5 Set: {2.5, 3.5} Size: 2 FINAL RESULT Distinct Averages Found SET 2.5 3.5 Number of distinct values: 2 OK - Answer: 2 2 distinct averages Key Insight: By sorting the array first, the minimum is always at the left pointer and maximum at the right pointer. Using a Set automatically handles duplicates, so we only count distinct averages. Time: O(n log n) for sorting | Space: O(n) for the Set TutorialsPoint - Number of Distinct Averages | Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
487 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