Mean of Array After Removing Some Elements — LeetCode 1619 Python Solution

EasyArraySorting
Problem
#1619
Pattern
Sorting
Reading time
2 min

The problem

Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements. Answers within 10-5 of the actual answer will be considered accepted.

Example

Input
arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]
Output
2.00000
Explanation
After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.

Python solution

Python
class Solution:
    def trimMean(self, arr: List[int]) -> float:
        n = len(arr)
        start, end = int(n * 0.05), int(n * 0.95)
        arr.sort()
        t = arr[start:end]
        return round(sum(t) / len(t), 5)

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1619. Mean of Array After Removing Some Elements is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1619. Mean of Array After Removing Some Elements?
LeetCode 1619. Mean of Array After Removing Some Elements is rated Easy on LeetCode.
What topics does LeetCode 1619. Mean of Array After Removing Some Elements cover?
LeetCode 1619. Mean of Array After Removing Some Elements is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview