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: Problem OverviewInput Array:4140Process: Remove Min/Max PairsStep 1: Remove 0 and 4 → Average = 2.0Step 2: Remove 1 and 4 → Average = 2.5Distinct Averages:2.02.5After sorting: [0, 1, 4, 4]0144MINMAXPair 1: (0+4)/2 = 2.014Pair 2: (1+4)/2 = 2.5Result: 2(2 distinct averages)
Understanding the Visualization
1
Input
Array of even length integers
2
Process
Repeatedly remove min/max pairs and calculate averages
3
Output
Count of distinct averages
Key Takeaway
🎯 Key Insight: Sorting allows us to efficiently pair minimum and maximum elements using two pointers
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