Minimum Operations to Make All Array Elements Equal - Problem

You're given an array nums of positive integers and multiple queries. For each query, you need to determine the minimum number of operations to make all elements in the array equal to a target value.

The only operation allowed is to increase or decrease any element by exactly 1. After each query, the array resets to its original state.

Goal: For each query value, calculate the total cost to transform all array elements to that value.

Example: If nums = [2, 7, 4] and query is 5, you need |2-5| + |7-5| + |4-5| = 3 + 2 + 1 = 6 operations.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [3,1,6,8], queries = [1,5]
โ€บ Output: [14,10]
๐Ÿ’ก Note: For query 1: |3-1| + |1-1| + |6-1| + |8-1| = 2+0+5+7 = 14. For query 5: |3-5| + |1-5| + |6-5| + |8-5| = 2+4+1+3 = 10
example_2.py โ€” Single Element
$ Input: nums = [2], queries = [3,1,2]
โ€บ Output: [1,1,0]
๐Ÿ’ก Note: For query 3: |2-3| = 1. For query 1: |2-1| = 1. For query 2: |2-2| = 0
example_3.py โ€” Large Values
$ Input: nums = [1,1000000], queries = [500000]
โ€บ Output: [999999]
๐Ÿ’ก Note: For query 500000: |1-500000| + |1000000-500000| = 499999 + 500000 = 999999

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i], queries[j] โ‰ค 106
  • 1 โ‰ค queries.length โ‰ค 105
  • All values are positive integers

Visualization

Tap to expand
๐ŸŒฑ Plant Height Adjustment (Target: 5 units)Height: 1Need +4Height: 2Need +3Height: 4Need +1Target: 5Height: 7Need -2Plants below target: +8 operationsPlants above target: +2 operationsTotal: 10 operations needed๐Ÿ’ก Binary search finds split point in O(log n)๐Ÿ“Š Prefix sums calculate costs in O(1)
Understanding the Visualization
1
Sort Plants
Arrange plants by current height: [1, 2, 4, 7]
2
Find Split Point
Use binary search to find where target height (5) would go
3
Calculate Adjustments
Plants below target need raising, plants above need lowering
4
Use Prefix Sums
Quickly calculate total adjustments using mathematical formulas
Key Takeaway
๐ŸŽฏ Key Insight: Sort once, then use binary search + prefix sums to answer each query in O(log n) time
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
28.5K Views
Medium-High 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