Ctrl K

Values Farthest From the Median

Medium
A sensor has sent a series of readings readings. An analyst wants the most unusual ones: those lying farthest from the median. Here the median is the element at index (n - 1) // 2 of the array sorted in ascending order, where n is the length of readings (for an even length that is the lower of the two middle values). Reading a is more unusual than reading b if |a - median| > |b - median|. When the distances are equal, the larger value is the more unusual one. Return the count most unusual readings in any order. Repeated values count as separate readings.
Example 1
readings=[4, 9, -2, 7, 5], count=2 → [-2, 9]

Sorted: [-2, 4, 5, 7, 9], so the median is 5. The farthest from it are -2 (7 away) and 9 (4 away).

Example 2
readings=[10, 2, 6, 8], count=3 → [10, 2, 8]

Sorted: [2, 6, 8, 10], so the median is the element at index (4 - 1) // 2 = 1, which is 6. Both 2 and 10 are 4 away and both are taken; 8 (2 away) comes third.

Example 3
readings=[3, 1, 5], count=1 → [5]

The median is 3, and both 1 and 5 are 2 away from it. On a tie the larger value wins, so the answer is 5.

Constraints
  • 1 ≤ len(readings) ≤ 10⁵
  • -10⁵ ≤ readings[i] ≤ 10⁵
  • 1 ≤ count ≤ len(readings)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsZero-Sum Triples MediumTriple Sum Nearest the Target MediumFour Numbers to a Target MediumFlags in Three Colors MediumStudios for Recording Sessions Medium
loading Python…
Input
readings=[4, 9, -2, 7, 5], count=2
Expected
[-2, 9]

Run checks the first 3 tests in your browser. Submit checks all 94 tests on the server, hidden ones included.