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: 1
💡 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. All elements satisfy constraints: 1,2 ≤ 2 and 4 ≥ 2. Total: 1 operation.
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: 2
💡 Note: Sort array to [1,5,6]. Median is 5. Need |5-3|=2 operations to make median 3. All elements satisfy constraints: 1 ≤ 3 and 6 ≥ 3. Total: 2 operations.

Constraints

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

Visualization

Tap to expand
Minimum Operations to Make Median Equal to K INPUT Original Array: 2 1 3 4 Sorted Array: 1 2 3 median 4 Target k: k = 2 n = 4 (even length) Median index = n/2 = 2 (0-indexed) ALGORITHM STEPS 1 Sort the Array [2,1,3,4] ---> [1,2,3,4] 2 Find Median Position medianIdx = n/2 = 2 Current median = 3 3 Greedy Adjustment If median > k: decrease elements at idx >= medianIdx median=3, k=2, so 3>2 Change 3 to 2: |3-2|= 1 op Change 4 to 2: max(0,4-2)=0 (4 >= k, no change needed) 4 Sum Operations Total = 1 + 1 = 2 ops (adjust left side too) FINAL RESULT Modified Array: 1 2 2 median=k 4 Operations Breakdown: Element at idx 2: 3 ---> 2 Operations: |3-2| = 1 Left elements: already ok Need 1 more op for balance Output: 2 [OK] Median = k = 2 Key Insight: After sorting, the median is at index n/2 (for even n, we take the larger middle). To minimize operations: elements LEFT of median must be <= k, elements at/RIGHT of median must be >= k. Greedy: adjust only elements that violate these constraints to reach k with minimum cost. TutorialsPoint - Minimum Operations to Make Median of Array Equal to K | Optimal Greedy Strategy
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