EasyNo. 1619

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

Pattern
Sorting
Topics
Array, 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

PythonSolution
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

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

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

Related problems
No.ProblemDifficulty
0056Merge IntervalsMedium
0164Maximum GapMedium
0274H-IndexMedium
0406Queue Reconstruction by HeightMedium
0414Third Maximum NumberEasy
0462Minimum Moves to Equal Array Elements IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.