Ctrl K

Nudge the Median

Medium
You are given an integer array scores and a number target. In one step you can increase or decrease any element by 1. The median of the array is its middle element once it is sorted in non-decreasing order. With an even number of elements there are two middle ones, and the larger of them counts as the median. Return the minimum number of steps needed to make the median of scores equal to target.
Example 1
scores=[3, 9, 4, 7, 8], target=5 → 2

Sorted, the scores are [3, 4, 7, 8, 9] and the median is 7. Lowering 7 to 5 takes 2 steps; 4 and 3 are already at most 5, so the median becomes 5. 2 steps in total.

Example 2
scores=[2, 2, 2, 6], target=4 → 2

The length is even, so the median is the larger middle element, index 2 after sorting, which is 2 now. Raise one of the 2s to 4 in 2 steps: [2, 2, 4, 6], and the median is 4.

Example 3
scores=[10], target=10 → 0
Constraints
  • 1 ≤ len(scores) ≤ 2·10⁵
  • 1 ≤ scores[i] ≤ 10⁹
  • 1 ≤ target ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Number From Pieces MediumStudios for Recording Sessions MediumLow, High, Low MediumStrictly Low, High, Low MediumFewest Meetings to Cancel Medium
loading Python…
Input
scores=[3, 9, 4, 7, 8], target=5
Expected
2

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