#2465
Number of Distinct Averages
EasyArrayHash TableTwo PointersSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By sorting the array first, we can efficiently pair the smallest and largest elements to compute averages. This reduces the need for repeated searches and allows us to directly access the elements we need.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array.
- 2Step 2: Initialize a set to store distinct averages.
- 3Step 3: Use a loop to iterate from the start to the midpoint of the array, pairing elements from the start and end.
- 4Step 4: Calculate the average for each pair and add it to the set.
- 5Step 5: Return the size of the set.
solution.py10 lines
1# Full working Python code
2
3def distinct_averages(nums):
4 nums.sort()
5 averages = set()
6 n = len(nums)
7 for i in range(n // 2):
8 avg = (nums[i] + nums[n - 1 - i]) / 2
9 averages.add(avg)
10 return len(averages)ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity remains O(n) for storing the distinct averages.
- 1Sorting the array allows for efficient pairing of elements.
- 2Using a set ensures that only distinct averages are stored.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.