Problem 1619

Abstract / Summary

Given an array of integers and a limit on removals find the maximum possible mean after removing up to that many elements.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1619.py

class Solution:
    def trimMean(self, arr: List[int]) -> float:
        five = len(arr) // 20
        arr  = sorted(arr)[five : -five]
        return sum(arr) / len(arr)
5 lines | 176 bytes | submitted February 23, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method trimMean. The method receives a list of integers, discards the lowest 5 % and the highest 5 % of the values, and returns the arithmetic mean of the remaining elements. The logic is compact, relying on Python’s built-in sorting and slicing capabilities to achieve the required trimming before performing the average calculation.

Key Steps

Determining the Trim Size

The first operation computes how many elements correspond to 5 % of the input length. Integer division ensures the result is an exact count, even when the list size is not a multiple of 20.

five = len(arr) // 20

Sorting and Removing Extremes

The list is sorted in ascending order, after which a slice removes the calculated number of elements from both the beginning and the end. The slice notation five : -five automatically handles the case where five is zero, leaving the list unchanged.

arr = sorted(arr)[five : -five]

Calculating the Mean

With the trimmed list in place, the method computes the sum of the remaining values and divides by the count of those values, yielding a floating-point result.

return sum(arr) / len(arr)

Edge Cases

When the input list length is less than 20, the integer division len(arr) // 20 yields zero. Consequently, five becomes zero, and the slicing operation arr[five : -five] evaluates to arr[0 : 0] if the list is empty after slicing, but Python treats a slice with identical start and end indices as an empty list. However, because five is zero, the slice expands to the full list (arr[0 : None]), effectively bypassing any trimming. This behavior gracefully handles very small inputs without raising errors.

If the list length is exactly 20, five equals 1, and the slice removes the single smallest and single largest elements, leaving 18 values for averaging. The code correctly processes this scenario because the slice boundaries are valid and the denominator len(arr) reflects the reduced size.

When the list contains duplicate values, the sorting step groups identical numbers together, and the slice removes the appropriate count from each end regardless of value distribution. This ensures that the trimming is based purely on positional rank rather than value uniqueness.

If the input list is empty, len(arr) // 20 yields zero, the sorted empty list remains empty, and the final division attempts sum([]) / len([]), which would raise a ZeroDivisionError. The code implicitly assumes that the problem constraints guarantee a non-empty list with sufficient length, and under those constraints the edge case does not arise.

Performance Optimizations

The implementation leverages Python’s highly optimized Timsort algorithm through the sorted built-in, which provides fast ordering for typical data patterns. By performing the sort once and then using slicing, the method avoids multiple passes over the data. The slicing operation creates a new list view without additional element-wise processing, and the subsequent sum call iterates over the trimmed list only once, minimizing the total number of element accesses.

Because the trimming size is derived from the total length, the slice boundaries are computed in constant time, and no auxiliary data structures are allocated beyond the sorted copy and the trimmed slice. This approach keeps memory usage proportional to the input size while ensuring that the most expensive operation-sorting-is performed a single time.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bag of colorful marbles, and each marble has a number written on it. This code is like building a smart machine to figure out the average number, but it wants to be extra fair by ignoring the tiny bit that is too small and the tiny bit that is too big.

First, the machine looks at all the marbles in the bag and counts them. It decides to take five percent of the marbles away from the bottom and five percent away from the top because it does not want those extreme numbers to change the result too much. It uses a clever trick with the division symbol to figure out exactly how many marbles to set aside.

Next, the machine lines all the marbles up in a row from the smallest number to the biggest number just like organizing your toys by size. It then chops off the beginning and the end of the line using the count it calculated earlier. Now, only the marbles in the middle part of the line remain.

Finally, the machine adds up all the numbers on those remaining marbles and divides that total by how many marbles are left in the group. This helps find a nice, balanced middle value that represents the whole collection well.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.48 | σ = 1.03

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
29 links | 17 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   February 23, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality