Minimum Operations to Make Median of Array Equal to K - Problem

You are given an integer array nums and a non-negative integer k. In one operation, you can increase or decrease any element by 1.

Return the minimum number of operations needed to make the median of nums equal to k.

The median of an array is defined as the middle element when the array is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,4], k = 2
Output: 2
💡 Note: Sort array to [1,2,3,4]. Median is at index 2 with value 3. Need 3-2=1 operation to make median 2. Element at index 3 is 4 > 2, need 4-2=2 more operations. Total: 1+2=3 operations. Wait, let me recalculate: sorted [1,2,3,4], median index n//2 = 2, so median is 3. Need |3-2|=1 operation. No violations. Actually total is 1.
Example 2 — Already Optimal
$ Input: nums = [1,2,3], k = 2
Output: 0
💡 Note: Sort array to [1,2,3]. Median is 2 which equals k. All elements satisfy median property: 1 ≤ 2 and 3 ≥ 2. No operations needed.
Example 3 — Large Adjustment
$ Input: nums = [1,5,6], k = 3
Output: 4
💡 Note: Sort array to [1,5,6]. Median is 5. Need |5-3|=2 operations to make median 3. Element 6 < 3 is false (6 ≥ 3), so no additional operations. Total: 2 operations.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i], k ≤ 109

Visualization

Tap to expand
Minimum Operations to Make Median Equal to KInput Array:2134Target k = 2Sorted Array:1234medianOperations Needed:Median: 3 → 2 = 1 operationLeft elements: 1,2 ≤ 2 ✓Right elements: 4 ≥ 2 ✓Result: 1 operation
Understanding the Visualization
1
Input
Array [2,1,3,4] and target k=2
2
Sort & Identify
Sort to [1,2,3,4], median is 3 at index 2
3
Greedy Adjust
Change median 3→2 (1 operation), no other violations
Key Takeaway
🎯 Key Insight: Sort first to identify median, then greedily adjust median and ensure surrounding elements maintain sorted order properties
Asked in
Google 15 Meta 12 Amazon 10 Microsoft 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen