#1619

Mean of Array After Removing Some Elements

Easy
ArraySortingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n log n)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages sorting but focuses on calculating the mean directly after determining the indices of the elements to remove. This avoids unnecessary storage and calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array.
  2. 2Step 2: Calculate the number of elements to remove (5% of the length of the array).
  3. 3Step 3: Calculate the sum of the remaining elements directly using a loop.
  4. 4Step 4: Calculate the mean using the sum and the count of remaining elements.
solution.py11 lines
1# Full working Python code
2
3def mean_after_removal(arr):
4    arr.sort()
5    n = len(arr)
6    remove_count = n // 20  # 5% of the array
7    total_sum = sum(arr[remove_count:n-remove_count])
8    return total_sum / (n - 2 * remove_count)
9
10# Example usage
11print(mean_after_removal([1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]))

Complexity note: The time complexity remains O(n log n) due to sorting, but we optimize the calculation of the mean by summing directly during the loop. The space complexity is O(1) as we are not using extra space proportional to input size.

  • 1Sorting is essential to identify the smallest and largest elements.
  • 2Removing a fixed percentage of elements simplifies the calculation of the mean.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.