Minimum Operations to Make All Array Elements Equal - Problem

You are given an array nums consisting of positive integers.

You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:

  • Increase or decrease an element of the array by 1.

Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].

Note: After each query the array is reset to its original state.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,4,6,8], queries = [3,1,5]
Output: [10,16,8]
💡 Note: Query 3: |2-3|+|4-3|+|6-3|+|8-3| = 1+1+3+5 = 10. Query 1: |2-1|+|4-1|+|6-1|+|8-1| = 1+3+5+7 = 16. Query 5: |2-5|+|4-5|+|6-5|+|8-5| = 3+1+1+3 = 8
Example 2 — Single Element
$ Input: nums = [1], queries = [5]
Output: [4]
💡 Note: Only one element: |1-5| = 4 operations needed
Example 3 — Target in Array
$ Input: nums = [1,2,3,4], queries = [2]
Output: [4]
💡 Note: Target 2 exists: |1-2|+|2-2|+|3-2|+|4-2| = 1+0+1+2 = 4

Constraints

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

Visualization

Tap to expand
Minimum Operations to Make Array Elements Equal INPUT nums array: 2 4 6 8 i=0 i=1 i=2 i=3 queries array: 3 1 5 Sorted nums: 2 4 6 8 Prefix sums: [0, 2, 6, 12, 20] n = 4, m = 3 ALGORITHM STEPS 1 Sort Array Sort nums for binary search 2 Build Prefix Sum prefix[i] = sum of first i items 3 Binary Search Find position for each query 4 Calculate Operations Use prefix sums for O(1) calc Query = 3 Example: Position: idx = 1 (3 > 2) Left cost: idx*q - prefix[idx] = 1*3 - 2 = 1 Right cost: (prefix[n]-prefix[idx]) - (n-idx)*q = 18 - 15 = 3 Total: 1 + 3 = 4 FINAL RESULT Operations for each query: Query = 3 |2-3|+|4-3|+|6-3|+|8-3| = 4 Query = 1 |2-1|+|4-1|+|6-1|+|8-1| = 14 Query = 5 |2-5|+|4-5|+|6-5|+|8-5| = 8 Output Array: 4 14 8 OK - Verified! Key Insight: Sorting + prefix sums enables O(1) query processing. For target value q, elements less than q need (idx * q - prefix[idx]) operations. Elements greater need (prefix[n] - prefix[idx] - (n-idx) * q). Total complexity: O(n log n + m log n) instead of naive O(n * m). TutorialsPoint - Minimum Operations to Make All Array Elements Equal | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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