Minimum Operations to Make Median of Array Equal to K solution and explanation
9 more videos on this problem
3107. Minimum Operations to Make Median of Array Equal to K | Adhoc | SortingAryan Mittal · 13:56 · 2K views
Weekly Contest 392 | Minimum Operations to Make Median of Array Equal to K CHECK COMMENT SECTIONkhasanm · 0:15 · 705 views
3107 Minimum Operations to Make Median of Array Equal to K ||(Updated question description) ✅ ||MathAyush Rao · 6:45 · 369 views
3107. Minimum Operations to Make Median of Array Equal to K (Leetcode Medium)Programming Live with Larry · 9:09 · 306 views
3107. Minimum Operations to Make Median of Array Equal to K || Leetcode Weekly Contest 392Ashish Kumar · 11:04 · 208 views
3107. Minimum Operations to Make Median of Array Equal to K | LEETCODE WEEKLY CONTEST 392code Explainer · 5:24 · 180 views
3107. Minimum Operations to Make Median of Array Equal to K | Leetcode Weekly 392 Contest | C++Priyanshi Porwal · 10:25 · 163 views
3107. Minimum Operations to Make Median of Array Equal to K | Weekly 392Tech Courses · 7:11 · 140 views
3107. Minimum Operations to Make Median of Array Equal to K | Weekly Contest 392 | LeetcodeRapid Syntax · 12:06 · 78 views
Solution - Leetcode 3107. Minimum Operations to Make Median of Array Equal to KShreshth Singh · 8:52 · 66 views
The 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 of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
Example 1:
Input: nums = [2,5,6,8,5], k = 4
Output: 2
Explanation:
We can subtract one from nums[1] and nums[4] to obtain [2, 4, 6, 8, 4]. The median of the resulting array is equal to k.
Example 2:
Input: nums = [2,5,6,8,5], k = 7
Output: 3
Explanation:
We can add one to nums[1] twice and add one to nums[2] once to obtain [2, 7, 7, 8, 5].
Example 3:
Input: nums = [1,2,3,4,5,6], k = 4
Output: 0
Explanation:
The median of the array is already equal to k.
Constraints:
1 <= nums.length <= 2 * 1051 <= nums[i] <= 1091 <= k <= 109
Approach overview
Problem Overview: You are given an integer array and a target value k. In one operation you can increment or decrement any element by 1. The goal is to make the median of the array exactly k using the minimum number of operations.
Approach 1: Sorting and Direct Manipulation (Time: O(n log n), Space: O(1))
Sort the array so the median index becomes deterministic at mid = n // 2. If nums[mid] == k, no work is needed. When the median is smaller than k, you must increase the median and any elements to its right that are still below k; otherwise the median would remain too small after sorting. Iterate from the median toward the right and accumulate k - nums[i] for every element smaller than k. When the median is larger than k, iterate left from the median and accumulate nums[i] - k for elements greater than k. This works because only values affecting the median position matter after sorting, making it a greedy adjustment. The algorithm relies on sorting and a simple array traversal.
Approach 2: Binary Search on Median Boundary (Time: O(n log n), Space: O(1))
After sorting, you can use binary search to locate the boundary where values cross k. For the case where the median must increase, binary search finds the first element greater than or equal to k on the right side. Every element between the median index and that boundary contributes k - nums[i] operations. If the median must decrease, binary search finds the last element less than or equal to k on the left side and sums nums[i] - k for the affected range. Binary search avoids scanning unnecessary elements and highlights the monotonic property created by sorting. This approach combines sorting with a greedy cost calculation.
Recommended for interviews: The sorting and direct manipulation approach is what interviewers typically expect. It shows you understand how the median behaves in a sorted array and which elements actually influence it. The binary search variant is a clean optimization and demonstrates deeper control over ordered data, but the greedy scan is usually sufficient and easier to reason about under interview pressure.
Approach 1: Sorting and Direct Manipulation
This approach involves sorting the array to identify the median and then calculating the number of operations needed to convert it to k. By sorting the array, we can easily fetch the median. Depending on whether the median is greater than or less than k, we calculate the total operations required by simply subtracting k from the median value.
def minOperations(nums, k):
nums.sort()
n = len(nums)
median_index = (n - 1) // 2
median = nums[median_index]
return abs(median - k)import java.util.Arrays;
public int minOperations(int[] nums, int k) {
Arrays.sort(nums);
int median = nums[(nums.length - 1) / 2];
return Math.abs(median - k);
}#include <algorithm>
#include <cmath>
#include <vector>
int minOperations(std::vector<int>& nums, int k) {
std::sort(nums.begin(), nums.end());
int median = nums[(nums.size() - 1) / 2];
return std::abs(median - k);
}function minOperations(nums, k) {
nums.sort((a, b) => a - b);
const medianIndex = Math.floor((nums.length - 1) / 2);
const median = nums[medianIndex];
return Math.abs(median - k);
}#include <stdio.h>
#include <stdlib.h>
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int minOperations(int* nums, int numsSize, int k) {
qsort(nums, numsSize, sizeof(int), compare);
int median = nums[(numsSize - 1) / 2];
return abs(median - k);
}using System;
public class Solution {
public int MinOperations(int[] nums, int k) {
Array.Sort(nums);
int median = nums[(nums.Length - 1) / 2];
return Math.Abs(median - k);
}
}First, sort the array nums. Determine the median index by using integer division on the length of the list minus one. Find the median from the sorted array and calculate the number of operations required to convert the median to k by taking the absolute difference.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(1) since sorting is done in-place.
Approach 2: Binary Search on Median
This approach optimizes the search by leveraging binary search methods to locate the median directly without a complete sort. It relies on partition methodology to determine the suitable pivot where the median lies.
def minOperations(nums, k):
def partition_around_median(l, r):
import random
pivot = nums[(l + r) // 2]
while l <= r:
while nums[l] < pivot:
l += 1
while nums[r] > pivot:
r -= 1
if l <= r:
nums[l], nums[r] = nums[r], nums[l]
l, r = l + 1, r - 1
return l
left, right = 0, len(nums) - 1
mid = len(nums) // 2
while left < right:
index = partition_around_median(left, right)
if index <= mid:
left = index
else:
right = index - 1
median = nums[mid]
return abs(median - k)function minOperations(nums, k) {
function partition(low, high) {
let pivot = nums[Math.floor((low + high) / 2)];
while (low <= high) {
while (nums[low] < pivot) low++;
while (nums[high] > pivot) high--;
if (low <= high) {
[nums[low], nums[high]] = [nums[high], nums[low]];
low++;
high--;
}
}
return low;
}
let low = 0, high = nums.length - 1;
let mid = Math.floor(nums.length / 2);
while (low < high) {
let partitionIndex = partition(low, high);
if (partitionIndex <= mid) {
low = partitionIndex;
} else {
high = partitionIndex - 1;
}
}
const median = nums[mid];
return Math.abs(median - k);
}The code attempts to find the median through partitioning that behaves akin to quickselect, a deterministic variant of quicksort. Instead of full sorting, it targets the section where the middle element resides. The computation focus is on adapting the middle value directly for needed operations.
Time Complexity: Average O(n) using partition-based median location (Quickselect).
Space Complexity: O(1) with in-place data manipulation.
Approach 3: Greedy + Sorting
First, we sort the array nums and find the position m of the median. The initial number of operations we need is |nums[m] - k|.
Next, we discuss in two cases:
- If
nums[m] > k, then all elements to the right ofmare greater than or equal tok. We only need to reduce the elements greater thankon the left ofmtok. - If
nums[m] \le k, then all elements to the left ofmare less than or equal tok. We only need to increase the elements less thankon the right ofmtok.
The time complexity is O(n times log n), and the space complexity is O(log n). Here, n is the length of the array nums.
function minOperationsToMakeMedianK(nums: number[], k: number): number {
nums.sort((a, b) => a - b);
const n = nums.length;
const m = n >> 1;
let ans = Math.abs(nums[m] - k);
if (nums[m] > k) {
for (let i = m - 1; i >= 0 && nums[i] > k; --i) {
ans += nums[i] - k;
}
} else {
for (let i = m + 1; i < n && nums[i] < k; ++i) {
ans += k - nums[i];
}
}
return ans;
}func minOperationsToMakeMedianK(nums []int, k int) (ans int64) {
sort.Ints(nums)
n := len(nums)
m := n >> 1
ans = int64(abs(nums[m] - k))
if nums[m] > k {
for i := m - 1; i >= 0 && nums[i] > k; i-- {
ans += int64(nums[i] - k)
}
} else {
for i := m + 1; i < n && nums[i] < k; i++ {
ans += int64(k - nums[i])
}
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}Complexity comparison
| Approach | Complexity |
|---|---|
| Sorting and Direct Manipulation | Time Complexity: O(n log n) due to the sorting operation. Space Complexity: O(1) since sorting is done in-place. |
| Binary Search on Median | Time Complexity: Average O(n) using partition-based median location (Quickselect). Space Complexity: O(1) with in-place data manipulation. |
| Greedy + Sorting | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Sorting and Direct Manipulation | O(n log n) | O(1) | Best general solution. Simple greedy scan after sorting. |
| Binary Search on Median Boundary | O(n log n) | O(1) | Useful when you want to quickly find the range of elements that must be adjusted. |
Frequently asked questions
Is Minimum Operations to Make Median of Array Equal to K easy or hard?
This problem is typically classified as Medium difficulty. The challenge comes from recognizing that only elements affecting the median after sorting matter. Once that insight is clear, the greedy adjustment becomes straightforward.
Minimum Operations to Make Median of Array Equal to K Python/Java solution
Implementations in Python, Java, C++, or JavaScript follow the same steps: sort the array, compute the median index, and accumulate the difference between elements and k depending on whether the median must increase or decrease. The logic remains identical across languages with O(n log n) time complexity.
How to solve Minimum Operations to Make Median of Array Equal to K in O(n)?
A strict O(n) solution is difficult because determining the median typically requires sorting or selection. Most implementations sort the array in O(n log n) and then adjust elements around the median. If a linear-time median selection algorithm is used, the adjustment phase can run in O(n), but this is rarely required in interviews.
What is the best approach for Minimum Operations to Make Median of Array Equal to K?
The most common solution sorts the array and directly adjusts elements affecting the median. After sorting, check the middle index and either increase elements on the right or decrease elements on the left until the median becomes k. This greedy approach runs in O(n log n) time due to sorting and uses O(1) extra space.
Is Minimum Operations to Make Median of Array Equal to K asked at Google/Amazon/Meta?
Median manipulation and greedy adjustment problems appear frequently in interviews at companies like Amazon, Google, and Meta. Variations involving medians, cost minimization, and sorted arrays are common because they test understanding of ordering properties and greedy reasoning.
What data structure is used in Minimum Operations to Make Median of Array Equal to K?
The primary data structure is a simple array. The algorithm relies on sorting the array and then iterating from the median index. No additional structures like heaps or hash maps are required for the optimal approach.
What is the time complexity of Minimum Operations to Make Median of Array Equal to K?
The optimal solution runs in O(n log n) time because the array must be sorted first. After sorting, a single linear scan from the median outward computes the required operations, which takes O(n). Space complexity is O(1) if sorting is done in-place.
