File: mean-of-array-after-removing-some-elements/solution.py

Date: 2026-06-06

Time: 17:45

mean-of-array-after-removing-some-elements/solution.py

Purpose

This file solves LeetCode 1619: Mean of Array After Removing Some Elements. It computes a 5% trimmed mean — the arithmetic mean of an integer array after discarding the smallest 5% and largest 5% of elements. The file is self-contained: solution class and test suite live in the same module.

Key Components

Solution.trimMean(arr: List[int]) -> float — The core algorithm. Given an array guaranteed to have length divisible by 20 (per the problem constraints), it:

1. Sorts the array in-place.

2. Computes k = len(arr) // 20 — the count of elements to remove from each end (5% of the total).

3. Slices the sorted array to arr[k : len(arr) - k], removing the bottom and top k elements.

4. Returns the mean of the remaining elements.

TestTrimMean — Six test cases covering the LeetCode examples, a uniform-value array, a 1000-element sequential array, and a boundary case with only two distinct values.

Patterns

Dependencies

Imports: typing.List (type annotation) and unittest (test framework). No project-internal dependencies.

Imported by: The test_solution.py file in this same directory, plus the massive list of cross-referencing test files in the repository (likely an artifact of the code-expert tooling indexing — those files don't actually import *this* solution, they follow the same structural pattern).

Flow


Input arr
  → sort in-place (ascending)
  → compute k = len(arr) // 20
  → slice arr[k : len(arr)-k]   # remove bottom/top 5%
  → sum(trimmed) / len(trimmed)
  → return float

The entire operation is O(n log n) dominated by the sort. The slice and sum are O(n).

Invariants

Error Handling

None. The code trusts LeetCode's input guarantees (non-empty array, length divisible by 20, integer elements in [0, 10^5]). An empty input would cause a ZeroDivisionError at the final division.

Topics to Explore

Beliefs