#2602

Minimum Operations to Make All Array Elements Equal

Medium
ArrayBinary SearchSortingPrefix SumPrefix SumSortingBinary Search
LeetCode ↗

Approaches

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

Intuition

Time O(n log n + m log n)Space O(n)

By sorting the nums array and using prefix sums, we can efficiently calculate the total operations needed for each query in linear time after the initial sort.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the nums array.
  2. 2Step 2: Create a prefix sum array where each element at index i is the sum of the first i elements of nums.
  3. 3Step 3: For each query, use binary search to find the position where the query would fit in the sorted nums array.
  4. 4Step 4: Calculate the total operations using the prefix sums for elements less than and greater than the query.
  5. 5Step 5: Store the result for each query and return the result array.
solution.py11 lines
1def minOperations(nums, queries):
2    nums.sort()
3    prefix_sum = [0] * (len(nums) + 1)
4    for i in range(1, len(nums) + 1):
5        prefix_sum[i] = prefix_sum[i - 1] + nums[i - 1]
6    result = []
7    for query in queries:
8        idx = bisect.bisect_left(nums, query)
9        total_operations = query * idx - prefix_sum[idx] + (prefix_sum[len(nums)] - prefix_sum[idx]) - query * (len(nums) - idx)
10        result.append(total_operations)
11    return result

Complexity note: The time complexity is O(n log n) for sorting the array and O(m log n) for processing each query using binary search, making it much more efficient than the brute force approach.

  • 1Using prefix sums allows for quick calculations of cumulative values, reducing the need for repeated summation.
  • 2Sorting the array enables efficient searching and comparison, which is crucial for optimizing the solution.

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