#2465
Easy Algorithms Number of distinct averages
Array Hash Table Two Pointers Sorting
58.9% acceptance
Feb 25, 2026
426
35
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 rem
oved. *
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn distinct_averages(nums: Vec<i32>) -> i32 {
use std::collections::HashSet;
let mut nums = nums;
nums.sort();
let n = nums.len();
let mut sums: HashSet<i32> = HashSet::new();
// store 2*average (= sum) to avoid floats
for i in 0..n / 2 {
sums.insert(nums[i] + nums[n - 1 - i]);
}
sums.len() as i32
}
}