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: [4,14,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: Transform Array Elements2468Original Array: nums = [2,4,6,8]315Queries: [3,1,5]Calculate operations for each queryQuery 3: |2-3|+|4-3|+|6-3|+|8-3| = 1+1+3+5 = 10Query 1: |2-1|+|4-1|+|6-1|+|8-1| = 1+3+5+7 = 16Query 5: |2-5|+|4-5|+|6-5|+|8-5| = 3+1+1+3 = 8Result: [10,16,8]
Understanding the Visualization
1
Input
Array [2,4,6,8] and queries [3,1,5]
2
Process
Calculate |nums[i] - query| for each element
3
Output
Total operations needed: [10,16,8]
Key Takeaway
🎯 Key Insight: Sorting the array enables efficient prefix sum calculations to avoid recalculating operations for each query
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