#3107

Minimum Operations to Make Median of Array Equal to K

Medium
ArrayGreedySortingSortingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach focuses on the properties of the median and how it can be adjusted efficiently without brute-forcing through all elements. By sorting the array and adjusting only the necessary elements, we minimize operations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: Identify the median index based on the length of the array.
  3. 3Step 3: If the current median is less than k, increase elements to k until the median is k.
  4. 4Step 4: If the current median is greater than k, decrease elements to k until the median is k.
solution.py20 lines
1# Full working Python code
2
3def min_operations(nums, k):
4    nums.sort()
5    n = len(nums)
6    median_index = (n - 1) // 2
7    current_median = nums[median_index]
8    operations = 0
9    if current_median < k:
10        for i in range(median_index, n):
11            if nums[i] < k:
12                operations += k - nums[i]
13    else:
14        for i in range(median_index + 1):
15            if nums[i] > k:
16                operations += nums[i] - k
17    return operations
18
19# Example usage
20print(min_operations([2,5,6,8,5], 4))  # Output: 2

Complexity note: The optimal solution has a time complexity of O(n log n) due to sorting the array, and a space complexity of O(1) since we are modifying the array in place.

  • 1Sorting the array is crucial to finding the median efficiently.
  • 2Only elements around the median need to be adjusted to minimize operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.