#3194
Minimum Average of Smallest and Largest Elements
EasyArrayTwo PointersSortingTwo PointersSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By sorting the array first, we can directly calculate the averages of pairs of elements from both ends of the sorted array. This eliminates the need for repeated searches for min and max.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array nums.
- 2Step 2: Initialize an empty list called averages.
- 3Step 3: For each index i from 0 to n/2 - 1, calculate the average of nums[i] and nums[n - i - 1] and add it to averages.
- 4Step 4: Return the minimum value from the averages list.
solution.py9 lines
1# Full working Python code
2
3def min_average(nums):
4 nums.sort()
5 averages = []
6 n = len(nums)
7 for i in range(n // 2):
8 averages.append((nums[i] + nums[n - i - 1]) / 2)
9 return min(averages)ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the averages.
- 1Sorting the array allows for efficient pairing of elements.
- 2The average of the smallest and largest elements converges towards the overall average.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.