Number of Distinct Averages - Problem
You're given an array of integers with even length. Your task is to perform a unique pairing operation that reveals how many distinct averages can be formed!
The Process:
- Find the minimum number in the array and remove it
- Find the maximum number in the remaining array and remove it
- Calculate the average of these two numbers:
(min + max) / 2 - Repeat until the array is empty
Goal: Return the count of distinct averages you calculated.
Example: For array [4,1,4,0,3,5]:
- Remove 0 (min) and 5 (max) → average = 2.5
- Remove 1 (min) and 4 (max) → average = 2.5
- Remove 3 (min) and 4 (max) → average = 3.5
Result: 2 distinct averages (2.5 and 3.5)
Input & Output
example_1.py — Basic Case
$
Input:
nums = [4,1,4,0,3,5]
›
Output:
2
💡 Note:
After sorting: [0,1,3,4,4,5]. 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.py — All Same Average
$
Input:
nums = [1,100]
›
Output:
1
💡 Note:
Only one pair possible: (1,100). Average = (1+100)/2 = 50.5. Only one distinct average, so return 1.
example_3.py — Multiple Distinct
$
Input:
nums = [9,5,7,8,7,9,8,2,0,7]
›
Output:
5
💡 Note:
After sorting: [0,2,5,7,7,7,8,8,9,9]. Pairs create averages: 4.5, 5.5, 6, 7.5, 8. Five distinct values.
Visualization
Tap to expand
Understanding the Visualization
1
Line Up by Personality
Sort everyone from most introverted to most extroverted
2
Pair from Extremes
Always pair the person at the left end with the person at the right end
3
Record Compatibility
Calculate their compatibility score (average) and add to our unique scores set
4
Move Inward
Remove the paired people and repeat with the next extremes
5
Count Unique Scores
Return the total number of distinct compatibility scores found
Key Takeaway
🎯 Key Insight: By sorting first and using two pointers from opposite ends, we eliminate the need for repeated searching and achieve optimal time complexity while maintaining clean, readable code!
Time & Space Complexity
Time Complexity
O(n log n)
Dominated by sorting step. The two-pointer traversal is O(n), but sorting takes O(n log n)
⚡ Linearithmic
Space Complexity
O(n)
Space for the set to store distinct averages, plus potential space for sorting depending on implementation
⚡ Linearithmic Space
Constraints
- 2 ≤ nums.length ≤ 100
- nums.length is even
- 0 ≤ nums[i] ≤ 100
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code